40 likes | 56 Views
Learn how to write and use constructors effectively with the new operator and grasp the significance of the "this" object in Java programming.
E N D
Recap: Constructors, the new operator and the this object • Three ideas: • How to write a constructor • How to use a constructor with the new operator • And why to use one • What the this object is The next several slides review each of these ideas
Writing Constructors A class can have many constructors, each with its own footprint (order and types of parameters) public class NameDropper extends StringTransformer implements StringTransformable { private String name; public NameDropper () { this.name = "Who knows" ; } public NameDropper(String givenName) { this.name = givenName; } public NameDropper (int givenNumber) { this.name = "Car " + GivenNumber; } public String transform(String x) { return this.name + " says " + x; } } This constructor can be used toinitialize the name fieldto the default value of “Who knows” This constructor can be used to initialize the name field with the given name This constructor can be used to initialize the name field as “Car number” Questions?
Using Constructors x1 = new NameDropper(); x1.transform("Hi")yields "Who knows says Hi" public class NameDropper extends StringTransformer implements StringTransformable { private String name; public NameDropper () { this.name = "Who knows" ; } public NameDropper(String givenName) { this.name = givenName; } public NameDropper (int givenNumber) { this.name = "Car " + GivenNumber; } public String transform(String x) { return this.name + " says " + x; } } x2 = new NameDropper("Ali"); x2.transform("Hi")yields "Ali says Hi" x3 = new NameDropper(54); x3.transform("Hi")yields "Car 54 says Hi" Questions? NameDropper x1, x2, x3; Write 3 statements that construct x1 .. x3 using the 3 constructors, respectively.
The this object x1 = new NameDropper(); x2 = new NameDropper("Ali"); x3 = new NameDropper(54); During execution of: x1.transform("Hi")the keyword this in NameDropper refers to the same object to which x1 refers. During execution of: x2.transform("Hi")the keyword this in NameDropper refers to the same object to which x2 refers. And so forth. Questions about what the keyword this means? public class NameDropper extends StringTransformer implements StringTransformable { private String name; public NameDropper () { this.name = "Who knows" ; } public NameDropper(String givenName) { this.name = givenName; } public NameDropper (int givenNumber) { this.name = "Car " + GivenNumber; } public String transform(String x) { return this.name + " says " + x; } }