Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument; should be placed in the first line in the constructor 11 this.x = x; 12 this.y = y; 13 } 14... 15 } Zheng-Liang Lu Java Programming 241 / 266
Exercise: Singleton In some situations, you may create the only instance of the class. 1 class Singleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static Singleton INSTANCE = new Singleton(); 5 6 // Do now allow to invoke the constructor by other classes. 7 private Singleton() {} 8 9 // Only way to obtain this singleton by the outside world. 10 public static Singleton getinstance() { 11 return INSTANCE; 12 } 13 } Zheng-Liang Lu Java Programming 242 / 266
Garbage Collection (GC) 1 Java handles deallocation automatically. Heuristics: period or memory stress. GC is the process of looking at the heap memory, identifying whether or not the objects are in use, and deleting the unreferenced objects. An object is said to be unreferenced if the object is no longer referenced by any part of your program. Simply assign null to the reference to make the object unreferenced. So the memory used by these objects can be reclaimed. 1 http://www.oracle.com/webfolder/technetwork/tutorials/obe/ java/gc01/index.html Zheng-Liang Lu Java Programming 243 / 266
finalize() The method finalize() conducts a specific task that will be executed right before the object is reclaimed by GC. For example, closing files and terminating network connections. The finalize() method can be only invoked prior to GC. In practice, it must not rely on the finalize() method for normal operations. (Why?) Zheng-Liang Lu Java Programming 244 / 266
Example 1 public class Garbage { 2 private static int numofobjkilled = 0; 3 4 public void finalize() { 5 numofobjkilled++; 6 } 7 8 public static void main(string[] args) { 9 double n = 1e7; 10 for (int i = 1; i <= n; i++) 11 new Garbage(); // lots of unreferenced objects 12 System.out.println(numOfObjKilled); 13 } 14 } You may try different number for instance creation. The number of the objects reclaimed by GC is uncertain. Zheng-Liang Lu Java Programming 245 / 266
HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation, stating that B exists independently from A. For example, knight sword; company employee. If A owns B, then it is a composition, meaning that B has no meaning or purpose in the system without A. For example, house room. Zheng-Liang Lu Java Programming 246 / 266
Example: Lines +2: two Point objects used in one Line object. Zheng-Liang Lu Java Programming 247 / 266
More Examples Circle, Triangle, and Polygon. Book with Authors. Lecturer and Students in the classroom. Zoo with many creatures, say Dog, Cat, and Bird. Channels played on TV. More. Zheng-Liang Lu Java Programming 248 / 266
More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism Packages: grouping related types, and providing access controls and name space management. Immutability Enumeration types Inner classes Zheng-Liang Lu Java Programming 249 / 266
First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class is a subclass of some class, which is so-called the superclass, by using the extends keyword. For example, B extends A. In semantics, B is a special case of A, or we could say B specializes A. For example, human and dog are two specific types of animals. When both B and C are subclasses of A, we say that A generalizes B and C. (Déjà vu.) Note that Java allows single inheritance only. Zheng-Liang Lu Java Programming 250 / 266
Example 1 class Animal { 2 String name; 3 int weight; 4 5 Animal(String s, int w) { name = s; weight = w; } 6 7 void eat() { weight++; } 8 void exercise() { weight ; } 9 } 10 11 class Human extends Animal { 12 Human(String s, int w) { super(s, w); } 13 void writecode() {} 14 } 15 16 class Dog extends Animal { 17 Dog(String s, int w) { super(s, w); } 18 void watchdoor() {} 19 } Zheng-Liang Lu Java Programming 251 / 266
Class Hierarchy 2 2 See Fig. 3-1 in p. 113 of Evans and Flanagan. Zheng-Liang Lu Java Programming 252 / 266
super Recall that the keyword this is used to refer to the object itself. You can use the keyword super to refer to (non-private) members of the superclass. Note that super() can be used to invoke the constructor of its superclass, just similar to this(). Zheng-Liang Lu Java Programming 253 / 266
Constructor Chaining As the constructor is invoked, the constructor of its superclass is invoked accordingly. You might think that there will be a whole chain of constructors called, all the way back to the constructor of the class Object, the topmost class in Java. So every class is an immediate or a distant subclass of Object. Recall that the method finalize() and tostring() are inherited from Object. tostring(): return a string which can be any information stored in the object. Zheng-Liang Lu Java Programming 254 / 266
Example 1 class A { 2 A() { System.out.println("A is creating..."); } 3 } 4 5 class B extends A { 6 B() { System.out.println("B is creating..."); } 7 // overriding tostring() 8 public String tostring() { return "I am B."; } 9 } 10 11 public class ConstructorChainingDemo { 12 public static void main(string[] args) { 13 B b = new B(); 14 System.out.println(b); 15 } 16 } The println() method (and similar methods) can take an object as input, and invoke tostring() method implicitly. Zheng-Liang Lu Java Programming 255 / 266
Method Overriding The subclass is allowed to change the behavior inherited from its superclass, if needed. If one defines an instance method with its method name, parameters, and also return type, all identical to the previously defined method in its superclass, then we say this newly-defined method overrides the one in the superclass. 3 Recall that method overloading occurs only in the same class. Note that you can invoke the overridden method through the use of the keyword super. 3 Notice that the static methods do not follow this rule. Zheng-Liang Lu Java Programming 256 / 266
Example Zheng-Liang Lu Java Programming 257 / 266
Binding Association of the method definition to the method call is known as binding. The binding which can be resolved at the compilation time is known as static binding or early binding. They are the static, private or final methods. 4 If the compiler is not able to resolve the binding, such binding is known as dynamic binding or late binding. For example, method overriding. 4 We will see the final keyword soon. Zheng-Liang Lu Java Programming 258 / 266
When there are multiple implementations of the method in the inheritance hierarchy, the one in the most derived class (the furthest down the hierarchy) always overrides the others, even if we refer to the object through a reference variable of the superclass type. 5 As you can see in Cat Simon. This is so-called subtype polymorphism. 5 An overridden method in Java acts like a virtual function in C++. Zheng-Liang Lu Java Programming 259 / 266
Polymorphism 6 The word polymorphism literally means many forms. Java allows 4 types of polymorphism: coercion (casting) ad hoc polymorphism (overloading) subtype polymorphism parametric polymorphism (generics) Modeling polymorphism in a programming language lets you create a uniform interface to different kinds of operands, arguments, and objects. 6 Read http://www.javaworld.com/article/3033445/learn-java/ java-101-polymorphism-in-java.html. Zheng-Liang Lu Java Programming 260 / 266
Example: Uniform Interface 1 class Student { 2 void domywork() { / Do not know the detail. /} 3 } 4 5 class HighSchoolStudent extends Student { 6 void writehomework() { 7 System.out.println("Write homework orz"); 8 } 9 10 void domywork() { writehomework(); } 11 } 12 13 class CollegeStudent extends Student { 14 void writereports() { 15 System.out.println("Write reports qq"); 16 } 17 18 void domywork() { writereports(); } 19 } Zheng-Liang Lu Java Programming 261 / 266
1 public class PolymorphismDemo { 2 3 public static void main(string[] args) { 4 HighSchoolStudent h = new HighSchoolStudent(); 5 gostudy(h); 6 CollegeStudent c = new CollegeStudent(); 7 gostudy(c); 8 } 9 10 // uniform interface, multiple implementations 11 // for future extension (scalability) 12 static void gostudy(student s) { 13 s.domywork(); 14 } 15 16 / no need to write these methods 17 static void gostudy(highschoolstudent s) { 18 s.writehomework(); 19 } 20 21 static void gostudy(collegestudent s) { 22 s.writereports(); 23 } 24 / 25 } Zheng-Liang Lu Java Programming 262 / 266
Subtype Polymorphism For convenience, let U be a subtype of T. Liskov Substitution Principle states that T-type objects may be replaced with U-type objects without altering any of the desirable properties of T (correctness, task performed, etc.). 7,8 7 See https://en.wikipedia.org/wiki/liskov_substitution_principle. 8 Also see https://en.wikipedia.org/wiki/solid_(object-oriented_design). Zheng-Liang Lu Java Programming 263 / 266
Casting Upcasting (widening conversion) is to cast the U object to the T variable. 1 T t = new U(); Downcasting (narrow conversion) is to cast the T variable to a U variable. 1 U u = (U) t; // t is T variable reference to a U object. Upcasting is always allowed, but downcasting is allowed only when a U object is passed to the U-type variable. Java type system makes sure that the referenced object provides services adequate for T type. Zheng-Liang Lu Java Programming 264 / 266
instanceof However, type-checking in compilation time is unsound. The operator instanceof checks if an object reference is an instance of a type, and returns a boolean value. Zheng-Liang Lu Java Programming 265 / 266
1 class T {} 2 class U extends T {} 3 Example 4 public class InstanceofDemo { 5 public static void main(string[] args) { 6 T t1 = new T(); 7 8 System.out.println(t1 instanceof U); // output false 9 System.out.println(t1 instanceof T); // output true 10 11 T t2 = new U(); // upcasting 12 13 System.out.println(t2 instanceof U); // output true 14 System.out.println(t2 instanceof T); // output true 15 16 U u = (U) t2; // downcasting; this is ok. 17 18 u = (U) new T(); // pass the compilation; fail during execution! 19 } 20 } Zheng-Liang Lu Java Programming 266 / 266