m idterm r eview goal: focus on concepts, not syntax
TRANSCRIPT
MIDTERM REVIEWGoal: focus on concepts, not syntax
EXAM 1 Covers all material so far except: Agile and git Questions are true/false, MC, short answer, and coding The following slides review material that students in the past
have found confusing The test is not limited to material in these slides. Your best
option is to review all ppts and (briefly) homework assignments
Past exams have been ~6 pages, 50 points. You should have time if you are prepared, but it will be long if you are not.
Coding: may include (but not limited to): exceptions, Junit, enumerated types, inheritance, UML, collections.
Review the UML exercise. Be sure that you can create a UML diagram.
Be sure you understand exceptions, including try/catch, throwing an exception, and the throws clause. Custom exceptions are NOT on the exam.
TOPICS File IO
why use Scanners? read from a file – only basics on test
Exceptions when/how to throw when/how to try/catch throws clause when to use checked/Exception vs
unchecked/RuntimeException create your own exception vs throw
Exception constructors
catching multiple exceptions propagation
Inheritance Abstract classes
final classes not covered Interfaces
Purpose How to use/create vs. Abstract Class
Collections maps and sets tree vs. hash when to use vs linked list, array
JUnit testing test file initialization exceptions @Before, @BeforeClass @Test how and why
Enum types application of enums (when) how to use own file vs. within other class create message – not on exam
UML diagram syntax associations, aggregations, dependencies arrows/directions line types
Java Basics Static Typecast Wrapper class
EXCEPTIONS AND FILE IO
FILE IO – WHY SCANNER? GENERAL• FileReader just “opens” file, accesses as “stream”• Scanner class has helpful functions (nextInt,
nextDouble, hasNext etc.)• We “wrap” a FileReader in a Scanner. Interesting
example of how classes may interact to provide functionality. Scanner takes stream… from where? anywhere!
• Then we use the Scanner to read the file – so we can get the next int, the next double, etc.• open: FileReader reader = new FileReader(filename);• read: using scanner • close: reader
• Biggest challenges for file io: can eclipse find the file? Does the format match what’s expected?
• Understanding exceptions more conceptually interesting/ relevant for test.
UNCHECKED
public void uncheckedException() {
Point p = null;
// Throws null pointer exception –
// RuntimeException, not checked
System.out.println(p.getX());
int[] nums = new int[5];
// Throws array index exception –
// RuntimeException, not checked
nums[6] = 15;
}Exceptions can only happen (be thrown) during program execution. This is true of ALL exceptions.
UNCHECKED – WHAT IF THESE WERE CHECKED?
public void uncheckedException() {
Point p = new Point(2,3);
// we’d need try/catch or throws for this
System.out.println(p.getX());
// and for this
System.out.println(p.getY());}
// and for this
System.out.println(p.getY()*2);
// and for this
System.out.println(p.getY()*2);}
}
Exceptions can only happen (be thrown) during program execution. This is true of ALL exceptions.
NullPointer is a logic error… should be fixed before deliver to customer
CHECKED EXCEPTION
public void loadFile() {
// This line generates a compiler error –
// FileNotFoundException is checked
// checked - compiler will NOT let you just ignore!
FileReader reader = new FileReader("input.txt");
}I’m checking on you!
Exceptions can only happen (be thrown) during program execution. This is true of ALL exceptions.
CHECKED EXCEPTIONS
If I test my program 50 times, can I ensure there will be no FileNotFoundException generated at the customer site?
NO So, Java compiler says:
You must acknowledge that opening the file may cause an error
You may handle this directly (with a try/catch) Or you may allow the caller of your method to
handle (with a throws clause)
THROWS CLAUSE AND TRY/CATCH One way to handle a checked exception is with try/catch
public void loadFile2() {
try {
FileReader reader = new FileReader("input.txt");
} catch (FileNotFoundException e) {
System.out.println(“File not found: input.txt”);
}
} Another way is with a throws clause
public void loadFile3() throws FileNotFoundException {
FileReader reader = new FileReader("input.txt");
}
WHICH TO USE?
Use a try/catch if this method knows how to handle the error Can the user re-enter a filename? Should I write the error to a log file? Should I abort the program? Does this function know?
Use a throws clause if the caller knows how to handle the error
This is a design decision – there is no right answer a priori!
ERROR PROPAGATION – WITH THROWS
main
init
loadAllFiles
loadConfig
calls
calls
calls
ERROR !
throws
throws
throws
If not handled here, throws clause from main will abort program
THROW VS THROWS CLAUSE Throws clause (previous slides) means an exception might
occur in this method (either one I detect, or one Java detects), and this method is not going to handle.
Syntax: public void fn() throws Exception { … }
Throw means there’s a condition that you as the programmer notice (e.g., bad format in Clue – Java wouldn’t know!).
So why throw an exception? If you can handle the error right there… you don’t!
Syntax: if (bad stuff I detect)
throw new Exception(“blah”);
WHY THROW AT ALL?
BankAccountbalance: 10call withdraw: 20
What do we do?
Bank Teller Program
ATM Website
BASIC CUSTOM EXCEPTION
public class MyException extends RuntimeException {
/* Good to have default constructor just in case */
public MyException() {
super();
}
/* This provides the message commonly displayed to users */
public MyException(String message) {
super(message); // Just calls super to set message
}
}
in another file: throw new MyException(“what a terrible failure!”);
DO I NEED A CUSTOM EXCEPTION?
If you just want to provide a meaningful message, just throw Exception
Custom exceptions are useful if you have additional processing, e.g., writing to a log file
You will not be asked to code a complex custom exception on the exam. But it’s good to know why you might want one.
You can throw your own message without creating a class: throw new Exception(“what a terrible failure!”);
CUSTOM – CHECKED VS UNCHECKED
If you want to force programmer to acknowledge this exception could occur:
public class MyException extends Exception { // code here} If you don’t want lots of try/catch or throwspublic class MyException extends
RuntimeException { // code here}
INHERITANCE
INHERITANCE – WHY AND SYNTAX Represents an “is-a” relationshippublic class Parent { /* variables.
private restricted to parent. protected accessible in child. package accessible in any class within package – not
really related to inheritancepublic would of course be accessible anywhere –
should typically only be used for constants
*/ /* constructor – initializes fields */ /* methods. Most are public, child inherits */}
INHERITANCE SYNTAX, CONTINUED
public class Child extends Parent {
/* additional variables, if any */
/* constructor. Typically call parent constructor, e.g.:
super(); // default constructor OR
super(field1, field2, … ,fieldn); */
/* can modify parent methods. Often call parent method, then add functionality */
@override // optional annotation, compiler ensures signature
public void someMethod() {
super.someMethod();
// extra stuff
}
Common to override Object methods: equals, clone, toString. Also hashcode (not covered)
ABSTRACT CLASSES AND INTERFACES
WHY DO WE CARE? One of the most frequent question in an interview for a
Junior/Graduate Developer role is ‘What is the difference between Abstract class and Interface?’. I have to admit that (as a Graduate) I thought this was not a good question to gauge my skill as a developer. I thought my intrepidness or whatever that skill I thought I had was far more important than being able to answer the difference between abstract and interface.
A couple of promotions later, I am sitting at the other end of the table. Having the responsibility of asking that same question, I can start to see to why we need to know the answer. To know the difference between the two, a developer must think about abstraction and encapsulation; the two paradigm that Object Oriented Programming heavily relies on in modelling reality. Without inheritance and interfaces, we are stuck with complex trees of conditions, iterations and recursions that is probably duplicated again and again to describe a similar characteristic between two entities.
http://www.ronaldwidha.net/2008/06/16/a-good-example-of-abstract-class-vs-interface/
PRACTICAL USE OF ABSTRACT CLASS In the system we develop, we have a class for starting
a data import. We have many different kinds of data imports, but most have some things in common: They read data from a file, they write it to the database, they produce an import protocol etc.
So we have an abstract class "Import", which contains implemented methods for things like writing protocol entries, finding all files to import, deleting processed import files etc. The specifics will be different for each import, so there are abstract methods that serve as extension hooks, e.g. getFilenamePattern() which is used by the reading method to find the files that can be imported. getFilenamePattern is implemented in the concrete subclass, depending on what kinds of files need to be imported.
That way, the shared import functionality is in one place, while the specifics for one kind of import are separate.
http://stackoverflow.com/questions/1509785/what-are-some-practical-examples-of-abstract-classes-in-java
A SIMPLE EXAMPLE
public abstract class Instructions {
// notice perform is not abstract
public void perform() {
firstStep();
secondStep();
thirdStep();
}
abstract void firstStep();
abstract void secondStep();
abstract void thirdStep();
}
ANOTHER EXAMPLE/* 'framework library' for a
person. A person can enroll and submit, however, the class that consumes this framework library needs to provide 'where' the paperwork needs to be sent */
public abstract Person {
public abstract void SendPaperWork(string paperwork)
public void Enroll() { SendPaperWork("enrolment");
}
public void Submit() {
SendPaperWork("report");
}}
/*by inheriting Person abstract class we are enabling student to enroll and submit, however, SendPaperWork need to be implemented because we need to tell it explicitly 'where' to send the enrolment/ submission
*/public class Student : Person { @overridepublic void SendPaperWork(string paperwork)
{ School.Send(paperwork); } } // an employee sends the paperwork to a
different 'place' than student public class Employee : Person { @overridepublic void SendPaperWork(string paperwork) { Company.Send(paperwork); } }
http://www.ronaldwidha.net/2008/06/16/a-good-example-of-abstract-class-vs-interface/
Vocabulary: concrete class has all methods defined
ABSTRACT CLASSES MAY CONTAIN
instance variables constants implemented functions abstract function (no function body)
If there are no abstract functions, then it should not be an abstract class
You cannot directly instantiate an abstract class (e.g., Instructions cmd = new Instructions(); not valid with previous example)
JAVA INTERFACE EXAMPLES
Interface: what (needed behavior) Implementation (separate class): how Examples:
ActionListener (actionPerformed) ActiveEvent (dispatch) Connection (interact with db) Set (clear, add, remove, contains, etc.) Tree/Hash List (add, get, isEmpty, etc.)
ArrayList/LinkedList/Vector/... Pageable (getPageFormat, getNumberOfPages, etc.)
What do pieces do in a game?
SYNTAX// keyword interfacepublic interface Moveable { // list required functionality // keyword abstract is optional, since they must be public void move(); // must be abstract! public void reverse(); // no method body, not even { }}// keyword implementspublic class Warrior implements Moveable { public void move() { … } public void reverse() { … } }
ABSTRACT CLASS VS INTERFACE
Use an abstract class when: there is common data (instance variables),
and/or some functionality can be defined, and some functionality depends on child class
Use an interface when: you are just specifying that certain behavior (i.e.,
methods) must exist no instance variables are allowed constants are allowed – why?
You cannot directly instantiate either an abstract class or an interface
CHOOSING A DATA TYPECollections
CHOOSING A DATA TYPE: ARRAY VS ARRAYLIST
Arrayint[] numbers = new int[5];int n = numbers[numbers.length]; // index exception•Fixed size•More efficient if large number of primitives (e.g., int)
ArrayListArrayList stuff = new ArrayList(); // heterogeneous, no type checkingArrayList<Integer> nums = new ArrayList<Integer>(); // must be Object childnums.add(“Cyndi”); // error! nums.add(new Integer(5)); nums.add(6); // autoboxing•Grows automatically•Includes some handy functionality
Converting between String/intString input = “5”;int in = Integer.parseInt(input);
CHOOSING A DATA TYPE: MAP// Flexible to declare using interface (example next slide)
Map<Integer, Customer> customers;
// But can’t instantiate an interface directly, this is wrong:
Map<Integer, Customer> customers = new Map<Integer, Customer();
// TreeMap puts in order, objects must be Comparable
TreeMap<Integer, Customer> customers = new TreeMap<Integer, Customer>();
// HashMap is efficient random access
HashMap<String, Integer> sightings;
125 Jack, 100 Main St, Somewhere, CO
230 Jill, 200 Elm St, Somewhere, COIf contiguous values, fixed size – could do as an array or ArrayList. Map is good semantics.
CHOOSING A DATA TYPE: SET No duplicates
Set<Student> club;
public JavaBasics() {// Only one place we need to specify
which implementationclub = new HashSet<Student>();}
public Set<Student> getClub() { return club;}
public void setClub(Set<Student> club) {
this.club = club;}
public class Student implements Comparable<Student>{
private String name;private double gpa;
@Override// Return negative if this < other, 0 if same,
positive if this > otherpublic int compareTo(Student other) { return name.compareTo(other.name);}
}
CHOOSING A DATA TYPE: LINKED LIST
Easy to insert at head Easy to insert between Easy to traverse Not good for direct access to specific target,
although Java does provide that capability.
head -> 5 5 5 /0
JUNIT
TEST FILE STRUCTURE – INSTANCE METHODSpublic TestMyClasses {
// instance var of test class
private ClassToTest classVar;
@Before
public void setUp() {
/* initializes classVar before every test method */
}
// If forget @Test, test is not executed
@Test
public void test1()
{ … }
@Test
public void test2()
{ … }
Sequence of calls:setUptest1setUptest2
Each call has its own instance of TestMyClasses, setUp is like a constructor
TEST FILE STRUCTURE – STATIC METHODSpublic TestMyClasses
// No instance variables needed
// No setup needed – no objects to initialize!
@Test
public void test1() {
// call the static method using the class name
[datatype] actual = ClassToTest.testMethod(param1, param2, … )
[datatype] expected = // calculate or otherwise determine value
Assert.assertEquals(actual, expected);
}
@Test
public void test2() {
Assert.assertTrue(//statement);
}
TEST FILE STRUCTURE – COMPLEX SETUPpublic TestMyClasses
private static [Class] classVar;
private [Class2] otherVar;
@BeforeClass
public static void doOnce() {
// initialize classVar, e.g., load Clue only needs to be done once }
@Before
public void setUp() {
// initialize otherVar before each test method
// can also access static variables
}
@Test
public void test1() { … }
@Test
public void test2() { … }
Sequence of calls:doOncesetUptest1setUptest2
This is not on the exam, just included for reference.
TESTING EXCEPTIONS
Need to call a function with a throws clause
loadOne, not loadAll
@Test expected=(Exception.class)
public void testBad() {
loadOne();
}
public void Class {
public void loadOne()
throws Exception {
if (format is bad…)
throw new
Exception(“Shame!”);
}
public void loadAll() {
try {
loadOne();
} catch (Exception e)
{// do something}
}
}
You won’t be asked to write this code on the exam.
ENUMERATED TYPES
WHY? HOW? WHEN?public class EnumDemo {
// create the type
public enum DoorDirection {RIGHT, LEFT, UP, DOWN, NONE };
// Declare a variable
private DoorDirection direction;
private int intDoorDirection;
private String strDoorDirection;
/* WHY? DayOfWeek, Gender, Marital status, ... */
public EnumDemo() {
// see how clear the enumerated type is!!
direction = DoorDirection.RIGHT;
// what direction is this????? Enum is better!
intDoorDirection = 2;
// will this match LEFT????? Enum is better!
strDoorDirection = "LFT";
}
public DoorDirection rotateDoorDirection() {
// check and set a variable, return it, could pass as parameter
if (direction == DoorDirection.UP) // Same class, just need Enum name
direction = DoorDirection.DOWN;
return direction;
} }
IN A SEPARATE FILEIn DoorDirection.java:
public enum DoorDirection {RIGHT, LEFT, UP, DOWN, NONE };
In Cell.java:
public class Cell {
private DoorDirection direction;
// other stuff
}
If inside another class:
public class ClueStuff {
public enum DoorDirection { RIGHT, LEFT, UP, DOWN, NONE};
}
In MoreClue.java:
public class MoreClue {
ClueStuff.DoorDirection direction;
}Info only, not on exam
UMLSelect slides from original lecture
TRANSLATING TO CODEpublic class Student { protected String name; // type not in UML private String address; // make reasonable private String email; // assumptions public boolean isEnrolled() {
return true; } // body not specified, return needed to compile}
public class GamePanel { public static final int CELL_SIZE = 20; private int whoseTurn;
public void drawBoard (Graphics g) { }}
final is a low-level detail, no consensus on whether/how to represent in UMLHow do we know it’s final? Class convention of ALL_CAPS
INHERITANCE IN UML Called a generalization relationship
Open triangle, points to parent
General
Specific
HINT: To remember direction, think that a child has only one parent, a parent may have many children. Our diagram has only one arrow – must point to parent. Think: child looks up to parent.
TRANSLATE TO CODE
public class Book { private String title; private String author; }
public class Textbook extends Book { private String course;}
public class Dictionary extends Dictionary{ private int numWords;}
NOTE: We do not repeat Title and Author in the child classes… instance variables are all inherited –
GENERAL RULE: Don’t clutter the diagram!
TRANSLATE TO CODE
// different ways to indicate abstract, we’re ignoringpublic abstract class Shape { private int x, y; public abstract void draw();}
public interface Comparable { public int compareTo(Object o);}
public class Book implements Comparable { private String title, author; public int compareTo(Object o) { …. }
HERE’S AN ASSOCIATION IN CODEpublic class Student {
private String name;
private Dog dog;
public Student(String name){
dog = new Dog();}public void takeAWalk() { dog.bark();}
}
public class Dog {
public void bark() {
System.out.println("Woof");
}
}
How does this help us design? Functions are put in various classes. Where does the functionality live? How can our classes work together to create a solution?
Note that Student has a variable of type Dog – but it does not appear in the UML as an attribute. Why?
HERE’S AN AGGREGATION IN CODEpublic class Car { private ArrayList<Wheel> wheels;}
public class Wheel {}
We will not make the distinction between aggregation and composition – these look no different in code.
Note the open diamond attached to the owner.
JAVA BASICS
STATIC VS INSTANCEpublic class StaticDemo {
private static int n;
private int z;
public void update(int amt) {
z = amt;
n = amt;
}
public void display() {
System.out.println("n = " + n + " z = " + z);
}
// static method… doesn’t need any instance variables
public static int calc(int a, int b) {
return a + b * 2;
}
public static void main(String[] args) {
StaticDemo sd = new StaticDemo();
StaticDemo sd2 = new StaticDemo();
sd.update(82);
sd2.update(15);
sd.display();
sd2.display();
System.out.println(StaticDemo.calc(5, 12));
}
}
displays n = 15 z = 82 n = 15 z = 15 29
TYPECASTS If you know that a reference contains a specific
type of object, you can perform a cast (will be an exception if you’re wrong)
BankAccount myAccount = (BankAccount) anObject;
Can use instanceof to test class type*if (anObject instanceof BankAccount){BankAccount myAccount = (BankAccount) anObject;
…}
*will be used very sparingly with good object-oriented design – rely on polymorphism instead. You may see this in an equals method, or with a non-parameterized ArrayList, etc. NOT ON EXAM.
WRAPPER CLASS
Primitives in Java have corresponding “wrapper” classes, e.g., int => Integer
A wrapper object stores a single value of the corresponding type
Wrappers also provide useful static conversion functions, such as Integer.parseInt, which takes a string and returns an int
Integer
5