Monthly Archives: September 2023

5.3 Chaining Constructors Using this() and super() A basic understanding of constructors (§3.7, p. 109) is beneficent for the discussion in this section. The this() Constructor Call Constructors cannot be inherited or overridden. They can be overloaded, but only in the same class. Since a constructor always has the same name as the class, each parameter list must be different when defining more than one constructor for a class. In Example 5.5, the class Light has three overloaded constructors. In the constructor at (3), the this reference is used to access the fields shadowed by the parameters. In the main() method at (4), the appropriate constructor is invoked depending on the arguments in the constructor call, as illustrated by the program output. Example 5.5 Constructor Overloading Click here to view code image Click here to view code image // File: DemoConstructorCall.javaclass Light {  // Fields:  private int     noOfWatts;      // wattage …

Read more

1/1