Final Methods in Classes – Object-Oriented Programming
Final Methods in Classes A final method in a class is a concrete method (i.e., has an implementation) and cannot be overridden or hidden in any subclass. Any normal class can declare a final method. The class need not be declared final. In Example 5.9, the non-final class Light defines the final method setWatts() at (10). Click here to view code image class Light { // (1) // … public final void setWatts(int watt) { // (10) Final instance method noOfWatts = watt; }} The subclass TubeLight attempts to override the final method setWatts() from the superclass Light at (14), which is not permitted. Click here to view code image class TubeLight extends Light { // (12) // … @Override public void setWatts(int watt) { // (14) Cannot override final method at (10)! noOfWatts = 2*watt; }} A call to a final method is bound at compile time; as such, a…
The super() Constructor Call – Object-Oriented Programming
The super() Constructor Call The constructor call super() is used in a subclass constructor to invoke a constructor in the direct superclass. This allows the subclass to influence the initialization of its inherited state when an object of the subclass is created. A super() call in the constructor of a subclass will result in the execution of the relevant constructor from the superclass, based on the signature of the call. Since the superclass name is known in the subclass declaration, the compiler can determine the superclass constructor invoked from the signature of the parameter list. A constructor in a subclass can access the class’s inherited members by their simple names. The keyword super can also be used in a subclass constructor to access inherited members via its superclass. One might be tempted to use the super keyword in a constructor to specify initial values for inherited fields. However, the super()…