20 likes | 154 Views
Instance Fields & Constructors. public class Greeter { private String myWord ; //instance field public String sayHello ( ) { String msg = “Hello “ + myWord +”!”; return msg ; } } // 1. Each Object of a class has it’s own unique set of “instance fields”.
E N D
Instance Fields & Constructors public class Greeter{ private String myWord; //instance field public String sayHello( ){ String msg = “Hello “ + myWord+”!”; return msg; } } // 1. Each Object of a class has it’s own unique set of “instance fields”. // 2. All instance fields should be private (data hiding <or> Encapsulation). // 3. Encapsulation -> process of hiding object data from outside access. • Instance Fields – Unique data associated with class objects. • Consider the following Greeter class: public Greeter( ) { //Constructor -> allows init of instance field myWord = “ Default”; // Same name as class. } // NO Return type. public Greeter(String str) { // Parameters determine myWord = str; // which one }// Overloading – methods w/same name, but? }
Open BlueJ-> Type in the following: public class Greeter{ private String myWord; // instance field public Greeter(String str) { // Assignment constructor myWord = str; } public Greeter( ) { // Default constructor myWord = “”; } public String sayHello( ) {// method( ) return “Hello “ + myWord +”!”; } } Now open a new class and type in the following: public class GreeterTest{ public static void main(String[] args){ Greeter worldGreeter = new Greeter(“World”); Greeter daveGreeter = new Greeter(“Dave”); Greeter defaultGreeter= new Greeter( ); System.out.println(worldGreeter.sayHello()); System.out.println(daveGreeter.sayHello()); System.out.println(defaultGreeter.sayHello()); } }