CLASS DEFINITION (FIELDS) public class Point { public int x; public int y; } Point p1 = new Point(); // currently x = 0, y = 0 Point p2 = new Point(); // currently x = 0, y = 0 p1.x = 16; p1.y = 32; p2.x = 25; p2.y = 50; System.out.println("(" + p1.x + ", " + p1.y + ")"); // (16, 32) System.out.println("(" + p2.x + ", " + p2.y + ")"); // (25, 50) Again, every instance has a distinct copy of fields
CLASS DEFINITION (FIELDS) package java.util; public class Point { int x; // Is protected by default (can only be read by java.util.*) int y; // Is protected by default (can only be read by java.util.*) } // Meanwhile, in another package package edu.just.cpe.MyNeatProject; Point p1 = new Point(); Point p2 = new Point(); p1.x = 16; // NOP. Compile error. p1.y = 32; // NOP. Compile error. p2.x = 25; // NOP. Compile error. p2.y = 50; // NOP. Compile error. System.out.println("(" + p1.x + ", " + p1.y + ")"); // ERROR. System.out.println("(" + p2.x + ", " + p2.y + ")"); // ERROR. Non-private fields can be read from an instance outside of the defining class, at a program point with field access
Constructors When you say new you allocate space for an object’s data. The result is an instance of your class, which has a unique personal copy of variables and shares the same behaviors (methods) -Implicitly, this also calls the class’s constructor
CLASS DEFINITION (CONSTRUCTOR) public class Point { private int x; private int y; public Point(int mx, int my) { x = mx; // assign parameter to field y = my; // assign parameter to field } Point p1 = new Point(3, 4); // currently, x = 3, y = 4 Point p2 = new Point(4, 8); // currently, x = 4, y = 8 Point p3; // p3 = null, no object constructed Constructors are special methods which are invoked after object creation (after new) By the time the constructor executes, the fields already have their default values (never uninitialized)