1 / 2

Instance Fields & Constructors

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”.

tivona
Download Presentation

Instance Fields & Constructors

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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? }

  2. 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()); } }

More Related