Example: Points in 2D Coordinate 1 class Point { 2 double x, y; // fields: data member 3 } 1 public class PointDemo { 2 public static void main(string[] args) { 3 // now create a new instance of Point 4 Point p1 = new Point(); 5 p1.x = 1; 6 p1.y = 2; 7 System.out.printf("(%d, %d)\n", p1.x, p1.y); 8 9 // create another instance of Point 10 Point p2 = new Point(); 11 p2.x = 3; 12 p2.y = 4; 13 System.out.printf("(%d, %d)\n", p2.x, p2.y); 14 } 15 } Zheng-Liang Lu Java Programming 233 / 257
Class Definition First, give a class name with the first letter capitalized, by convention. The class body, surrounded by balanced braces {}, contains data members (fields) and function members (methods) for objects. We may need an entry point to run the program if the class is used to run the whole program. Zheng-Liang Lu Java Programming 234 / 257
Data Members The fields are the states of the object. May have an access modifier, say public and private. public: accessible from all classes private: accessible only within its own class Access modifiers realize encapsulation! In other word, you can decide if these fields are accessible! In OO practice, all the fields should be declared private. Zheng-Liang Lu Java Programming 235 / 257
Function Members As said, the fields are hidden by encapsulation. So we may need accessors and mutators if necessary. Accessors: return the state of the object Mutators: set the state of the object For example, getx() and gety() are accessors, and setpoint(double, double) is a mutator in the class Point. Zheng-Liang Lu Java Programming 236 / 257
Example: Point (Encapsulated) 1 class Point { 2 private double x; 3 private double y; 4 5 double getx() { return x; } 6 double gety() { return y; } 7 8 void setx(double a) { x = a; } 9 void sety(double a) { y = a; } 10 void setpoint(double a, double b) { 11 x = a; 12 y = b; 13 } 14 } Zheng-Liang Lu Java Programming 237 / 257
Unified Modeling Language 1 Unified Modeling Language (UML) is a tool for specifying, visualizing, constructing, and documenting the artifacts of software systems, as well as for business modeling and other non-software systems. Free software: http://staruml.io/ (available for all platforms) 1 See http://www.tutorialspoint.com/uml/ and http://www.mitchellsoftwareengineering.com/introtouml.pdf. Zheng-Liang Lu Java Programming 238 / 257
Example: Class Diagram for Point Modifiers are placed before the fields and the methods: + for public for private Zheng-Liang Lu Java Programming 239 / 257
Constructors A constructor is called by the new operator. Constructors are like special methods except that they use the name of the class and have no return type. Note that the constructors are not the part of the instances. As with methods, the constructors can be overloaded. If you don t define an explicit constructor, Java assumes a default constructor for your class. Moreover, adding any explicit constructor disables the default constructor. Zheng-Liang Lu Java Programming 240 / 257
Parameterized Constructors You can provide specific information to the parameterized constructor as the object is instantiated. For example, 1 class Point { 2... 3 4 Point() {} // restore a default constructor; 5 6 // parameterized constructor 7 Point(double a, double b) { 8 x = a; 9 y = b; 10 } 11... 12 } Zheng-Liang Lu Java Programming 241 / 257
Example: Point (Revisited) 1 public class PointDemo { 2 public static void main(string[] args) { 3 Point p1 = new Point(1, 2); 4 System.out.printf("(%f, %f)", p1.getx(), p1.gety()); 5 // output (1, 2) 6 } 7 } Zheng-Liang Lu Java Programming 242 / 257
Self-reference You can refer to any (instance) member of the current object within methods and constructors by using this. The most common reason for using the this keyword is because a field is shadowed by method parameters. You can also use this to call another constructor in the same class by invoking this(). Zheng-Liang Lu Java Programming 243 / 257
Example: Point (Revisited) 1 class Point { 2... 3 Point(int x, int y) { 4 this.x = x; 5 this.y = y; 6 } 7... 8 } Note that the this operator is referenced to instance members only, but not members declared static. Zheng-Liang Lu Java Programming 244 / 257
Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these instance members are available only when the object is created. Those declared w/ static are static members, aka class members. Zheng-Liang Lu Java Programming 245 / 257
Zheng-Liang Lu Java Programming 246 / 257
Static Members Static members mean that there is only one copy of the static members, no matter how many objects of the class are created. The static members belong to the class, and are shared between the instance objects. They are ready once the class is loaded. They can be invoked directly by the class name without creating an instance. For example, Math.random(). Zheng-Liang Lu Java Programming 247 / 257
A static method can access other static members. However, static methods cannot access to instance members directly. (Why?) For example, 1... 2 double getdistancefrom(point p) { 3 return Math.sqrt(Math.pow(this.x p.x, 2) + Math.pow( this.y p.y, 2)); 4 } 5 6 static double distancebetween(point p1, Point p2) { 7 return Math.sqrt(Math.pow(p1.x p2.x, 2) + Math.pow(p1. y p2.y, 2)); 8 } 9... Zheng-Liang Lu Java Programming 248 / 257
Example: Count of Points 1 class Point { 2... 3 private static int cnt = 0; 4 5 Point() { 6 cnt++; 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... 16 } Zheng-Liang Lu Java Programming 249 / 257
Exercise: Singleton 2 In some situations, you may create the only instance of the class. 1 class mysingleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static mysingleton Instance = new mysingleton(); 5 6 // Do now allow to invoke the constructor by other classes. 7 private mysingleton() {} 8 9 // Only way to obtain the singleton from the outside world. 10 public static mysingleton getsingleton() { 11 return Instance; 12 } 13 } 2 See any textbook for design patterns. Zheng-Liang Lu Java Programming 250 / 257
Garbage Collection (GC) 3 Java handles deallocation automatically. Automatic garbage collection 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-type variable to make the object referenced by this variable unreferenced. So the memory used by these objects can be reclaimed. 3 http://www.oracle.com/webfolder/technetwork/tutorials/obe/ java/gc01/index.html Zheng-Liang Lu Java Programming 251 / 257
finalize() Method The method finalize() conducts a specific task that will be executed as soon as the object is about to be reclaimed by GC. 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 252 / 257
Example 1 public class finalizedemo { 2 static int numofpointkilled = 0; 3 4 public void finalize() { 5 numofpointkilled++; 6 } 7 8 public static void main(string[] args) { 9 double n = 1e7; 10 for (int i = 1; i <= n; i++) 11 new finalizedemo(); 12 System.out.println(numOfPointKilled); 13 } 14 } You may try different number for instance creation. The number of the objects reclaimed by GC is not deterministic. Zheng-Liang Lu Java Programming 253 / 257
HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all objects have their own lifecycle, but there is ownership and child objects can not belong to another parent object. For example, knight sword Composition is a specialized form of aggregation and we can call this as a death relationship. For example, house room Zheng-Liang Lu Java Programming 254 / 257
Example: Lines on 2D Cartesian Coordinate +2: two Point objects contained in a Line object. Zheng-Liang Lu Java Programming 255 / 257
More Examples More geometric objects, say Circle, Triangle, and Polygon. Complex number (a + bi) equipped with + and so on. Book with Authors. Lecturer and Students in the classroom. Zoo with many creatures, say Dog, Cat, and Bird. Channels played on TV. Zheng-Liang Lu Java Programming 256 / 257
More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to the outside world Packages: grouping related types, providing access protection and name space management Zheng-Liang Lu Java Programming 257 / 257