CLASS DEFINITION FIELDS public class Point public int

CLASS DEFINITION (FIELDS) public class Point { public int x; public int y; } Point p 1 = new Point(); // currently Point p 2 = new Point(); // currently p 1. x = 16; p 1. y = 32; p 2. x = 25; p 2. y = 50; System. out. println("(" + p 1. x + ", " System. out. println("(" + p 2. x + ", " x = 0, y = 0 + p 1. y + ")"); // (16, 32) + p 2. 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 edu. just. cpe. My. Neat. Project; Point p 1 = new Point(); Point p 2 = new Point(); p 1. x = 16; // NOP. Compile error. p 1. y = 32; // NOP. Compile error. p 2. x = 25; // NOP. Compile error. p 2. y = 50; // NOP. Compile error. System. out. println("(" + p 1. x + ", " + p 1. y + ")"); // ERROR. System. out. println("(" + p 2. x + ", " + p 2. y + ")"); // ERROR. Non-private fields can be read from an instance outside of the defining class, at a program point with field

Constructors q When you say new you allocate space for an object’s data. q 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 p 1 = new Point(3, 4); // currently, x = 3, y = 4 Point p 2 = new Point(4, 8); // currently, x = 4, y = 8 Point p 3; // p 3 = 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)
- Slides: 4