Maria Hello Rumi says Hello Maria says Hello

  • Slides: 3
Download presentation
Maria Hello Rumi says Hello Maria says Hello • One class can describe many

Maria Hello Rumi says Hello Maria says Hello • One class can describe many different instances – Two Name. Droppers, each with their own my. Name field • In Java, the transform method for Name. Dropper is: String transform(String the. Phrase) { return this. my. Name + " says " + the. Phrase; } – this. my. Name means this instance’s my. Name field Fundamentals of Software Development 1 1

Fields and Constructors • A Name. Dropper must know its name from the very

Fields and Constructors • A Name. Dropper must know its name from the very beginning – We use a constructor to set the field called my. Name: Name. Dropper(String what. My. Name. Is) { this. my. Name = what. My. Name. Is; } – Then, when we invoke Name. Dropper’s constructor, we give it an argument: new Name. Dropper("Rumi"); new Name. Dropper("Maria"); Fundamentals of Software Development 1 2

Class: Fields, Constructors, Methods public class Name. Dropper extends String. Transformer implements String. Transformable

Class: Fields, Constructors, Methods public class Name. Dropper extends String. Transformer implements String. Transformable { private String name; // field: persistent storage, a permanent part // of each Name. Dropper public Name. Dropper(String what. My. Name. Is) { this. name = what. My. Name. Is; } // Constructor public String transform(String what. To. Say) { // Method return this. name + " says " + what. To. Say; } } Fundamentals of Software Development 1 Private means private to the class. The standard is that fields are generally private and all else is public (for now) – more on this later. Questions? 3