Monthly Archives: April 2023

Final Fields in Classes A final field must be explicitly initialized only once with an initializer expression, either in its declaration or in an initializer block. A final instance field can also be initialized in a constructor. After the class completes initialization, the final static fields of the class are all guaranteed to be initialized. After a constructor completes execution, the final instance fields of the current object are all guaranteed to be initialized. The compiler ensures that the class provides the appropriate code to initialize the final fields. In Example 5.9, the class Light defines two final static fields at (2) and (3). The field KWH_PRICE is a constant variable that is initialized by the constant expression 3.25 in the declaration at (2). The field MANUFACTURER is a blank final static field that is initialized in the static initializer block at (4). All static initializer blocks are executed at…

Read more

Extending an abstract Class A class might choose the design strategy with abstract methods to dictate certain behavior, but allow its subclasses the freedom to provide the relevant implementation. An abstract class forces its subclasses to provide the subclass-specific functionality stipulated by its abstract methods, which is needed to fully implement its abstraction. In other words, subclasses of the abstract class have to take a stand and provide implementations of any inherited abstract methods before objects can be created. In Example 5.8, since the class Light is abstract, it forces its concrete (i.e., non-abstract) subclass to provide an implementation for the abstract method energyCost(). The concrete subclass TubeLight provides an implementation for this method at (3). Click here to view code image class TubeLight extends Light {  // …  // Implementation of the abstract method from the superclass.  @Override public double energyCost(int noOfHours) {      // (3)    return  0.15 * noOfHours; …

Read more

2/2