530 likes | 626 Views
Midterm Review. Goal: 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
E N D
Midterm Review Goal: 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 • The test is 7 pages, 100 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 a) translate from a rough description to UML and b) translate from UML to code. • Be sure you understand exceptions, including try/catch, throwing an exception, and the throws clause.
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
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);} } NullPointer is a logic error… should be fixed before deliver to customer Exceptions can only happen (be thrown) during program execution. This is true of ALL exceptions.
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 If not handled here, throws clause from main will abort program calls throws init calls throws loadAllFiles calls throws loadConfig ERROR !
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? What do we do? BankAccount balance: 10 call withdraw: 20 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 throws public class MyException extends RuntimeException { // code here }
Inheritance – why and syntax • Represents an “is-a” relationship public class Parent { /* variables. private restricted to parent. protected accessible in child. package accessible in any class within package – not really related to inheritance public 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)
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 { @override public void SendPaperWork(string paperwork) { School.Send(paperwork); } } // an employee sends the paperwork to a different 'place' than student public class Employee : Person { @override public void SendPaperWork(string paperwork) { Company.Send(paperwork); } } Vocabulary: concrete class has all methods defined http://www.ronaldwidha.net/2008/06/16/a-good-example-of-abstract-class-vs-interface/
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: 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 interface public 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 implements public 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 type Collections
Choosing a data type: Array vsArrayList Array int[] numbers = new int[5]; int n = numbers[numbers.length]; // index exception • Fixed size • More efficient if large number of primitives (e.g., int) ArrayList ArrayList stuff = new ArrayList(); // heterogeneous, no type checking ArrayList<Integer> nums = new ArrayList<Integer>(); // must be Object child nums.add(“Cyndi”); // error! nums.add(new Integer(5)); nums.add(6); // autoboxing • Grows automatically • Includes some handy functionality Converting between String/int String 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 Jill, 200 Elm St, Somewhere, CO 230 If 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 implementation club = 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 > other public intcompareTo(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. 5 5 /0 5 head ->
Test file Structure – instance methods public TestMyClasses { // instance var of test class private ClassToTestclassVar; @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: setUp test1 setUp test2 Each call has its own instance of TestMyClasses, setUp is like a constructor
Test file Structure – Static methods public 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 setup public 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: doOnce setUp test1 setUp test2 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.
Why? How? When? public class EnumDemo { // create the type public enumDoorDirection {RIGHT, LEFT, UP, DOWN, NONE }; // Declare a variable private DoorDirection direction; private intintDoorDirection; 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 DoorDirectionrotateDoorDirection() { // 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 file In 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
UML Select slides from original lecture
Translating to code public 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 UML How do we know it’s final? Class convention of ALL_CAPS
Inheritance in UML • Called a generalization relationship General Open triangle, points to parent 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 ignoring public 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 code public 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"); } } Note that Student has a variable of type Dog – but it does not appear in the UML as an attribute. Why? 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?
Here’s an aggregation in code public class Car { private ArrayList<Wheel> wheels; } public class Wheel { } Note the open diamond attached to the owner. We will not make the distinction between aggregation and composition – these look no different in code.