Outline

Reminders

Classes Constructors References Balloon b1=null; // no Balloons exist, we have 1 reference to Balloon // b1 is of type Reference to Balloon // b1 holds the address of a Balloon (or it will) // b1.inflate(5); // gets null pointer exception // Exception in thread "main" java.lang.NullPointerException // at Balloon.main(Balloon.java:8) new Balloon(); // Call first constructor // One new Balloon is created, but no one can talk to it, we lost its phone number b1 = new Balloon(20, "green"); System.out.println(b1.toString()); System.out.println(b1); // Same as above, default call to toString Balloon b2 = new Balloon(30, "blue"); // All in one line: Array of References Balloon [] ba; // Reference to (array of reference to Balloon) // No array of reference to Balloon exists yet!!! ba = new Balloon[10]; // now have an array of 10 reference to Balloon // no new Balloon created!!! // Notice ba[0], ..., ba[9] all have type reference to Balloon for(int i=0; i<ba.length; i++){ ba[i]=new Balloon(i*10); } Overloading Protection /** * Modifier Class Package Subclass World * public Y Y Y Y * protected Y Y Y N * no modifier Y Y N N * private Y N N N **/ Javadoc Static private static int numCreated = 0; private static int numPopped = 0; public Balloon(int capacity, String colour){ Balloon.numCreated ++; // look in class ... } public static void printPopulation(){ System.out.println("numCreated="+numCreated); System.out.println("numPopped="+numPopped); // System.out.println("capacity="+this.capacity); // can't reference from a static context } Search for Names in a Single Class Modifying search Misc

Unit Testing

JUnit

See: JUnit 5 and the JUnit 5 api

Inheritance in Java


Search for Method Names (again)

Search for Variables (again)

Overriding and Shadowing

Abstract Classes

Who Inherits from Whom?

  • Question: What should the relationship be between the following classes? Shape Circle Rectangle Square
  • Liskov Substitution Principle (LSP): "Objects of subtypes should behave like those of supertypes if used via supertype methods."

    Functions that use references to parent classes must be able to use objects of child classes without knowing it. In other words, methods in the parent class must make total sense for the child class.
  • If Square is a subclass of Rectangle, then Rectangle setWidth() and setHeight() methods do NOT make sense for Square. Violating LSP. Square should directly inherit from Shape.
  • On stack overflow

    UML

    UML Class Notation