tivona
Uploaded by
2 SLIDES
165 VUES
20LIKES

Understanding the Greeter Class in Java: Constructors and Instance Fields

DESCRIPTION

This text explores the Greeter class in Java, emphasizing the concept of instance fields and constructors. Each object of the Greeter class has its own unique set of instance fields, which should be private to maintain encapsulation and data hiding. The class includes two constructors: one for a default instance and another that takes a string to set the instance field. An example is provided, demonstrating how to create and use Greeter objects in a test class to print personalized greetings. This highlights the importance of encapsulation and method overloading in OOP.

1 / 2

Télécharger la présentation

Understanding the Greeter Class in Java: Constructors and Instance Fields

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