The for(:) Statement – Control Flow
4.8 The for(:) Statement The enhanced for loop is convenient when we need to iterate over an array or a collection, especially when some operation needs to be performed on each element of the array or collection. In this section we discuss iterating over arrays. In §15.2, p. 795, we take a look at the for(:) loop for iterating over collections. Earlier in this chapter we used a for(;;) loop to sum the values of elements in an int array: Click here to view code image int sum = 0;int[] intArray = {12, 23, 5, 7, 19};for (int index = 0; index < intArray.length; index++) { // (1) using for(;;) loop sum += intArray[index];} The for(;;) loop at (1) is rewritten using the for(:) loop in Figure 4.9. Figure 4.9 Enhanced for Statement The body of the loop is executed for each element in the array, where the variable element…
Implementing Interfaces – Object-Oriented Programming
Implementing Interfaces A class can implement, wholly or partially, any number of interfaces. A class specifies the interfaces it implements as a comma-separated list of unique interface names in an implements clause in the class header. Implementing an interface essentially means that the class must provide implementation for the abstract methods declared in the interface. In fact, an abstract method declaration is overridden when an implementation is provided by a class. Optionally, the class can also override any default methods if necessary. The criteria for overriding methods in classes also apply when implementing abstract and any default methods from interfaces. A class must provide a method implementation with the same method signature and (covariant) return type as the declaration in the interface, and it can neither narrow the public access of the method nor specify new exceptions in the method’s throws clause, as attempting to do so would amount to…
Interface Evolution – Object-Oriented Programming
Interface Evolution Augmenting an existing interface with an abstract method will break all classes that implement this interface, as they will no longer implement the old interface. These classes will need to be modified and recompiled in order to work with the augmented interface. Augmenting an existing interface with a default method does not pose this problem. Classes that implement the old interface will work with the augmented interface without modifying or recompiling them. Thus interfaces can evolve without affecting classes that worked with the old interface. This is also true for static methods (p. 251) added to existing interfaces. Example 5.13 Inheriting Method Implementations from Supertypes Click here to view code image // File: MultipleInheritance2.javaclass Slogan { public void printSlogan() { // (1) Concrete method System.out.println(“Superclass wins!”); }}//_______________________________________________________________________________interface ISlogan { default void printSlogan() { // (2) Default method System.out.println(“Superinterface wins!”); }}//_______________________________________________________________________________class MySlogan extends Slogan implements ISlogan { } //…
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()…
Final Variables – Object-Oriented Programming
Final Variables A final variable is a variable whose value cannot be changed during its lifetime once it has been initialized. A final variable is declared with the keyword final in its declaration. Any attempt to reassign a value will result in a compile-time error. Declaring a variable as final has the following implications: For all paths of execution through the code, the compiler checks that a final variable is assigned only once before it is accessed, and when in doubt, the compiler issues an error (p. 232). A blank final variable is a final variable whose declaration does not specify an initializer expression. A constant variable is a final variable of either a primitive type or type String that is initialized with a constant expression. Constant variables can be used as case labels of a switch statement. We distinguish between two kinds of final variables: final fields that are…
Final Local Variables in Methods – Object-Oriented Programming
Final Local Variables in Methods A final local variable need not be initialized in its declaration—that is, it can be a blank final local variable—but it must be initialized in the code before it is accessed. However, the compiler does not complain as long as the local variable is not accessed—this is in contrast to final fields that must be explicitly assigned a value, whether they are accessed or not. In Example 5.9, the main() method at (15) in the class Warehouse defines a final local reference workLight at (16). The state of the object denoted by the reference workLight is changed at (17), but an attempt to change the value of the final instance field color of this object at (18) does not succeed. The compiler also reports an error at (19), since the reference value of the final local variable work-Light cannot be changed. A blank final local…
Final Declarations – Object-Oriented Programming
5.5 Final Declarations The keyword final can be used in the following contexts in Java: Final Classes A class can be declared final to indicate that it cannot be extended—that is, one cannot define subclasses of a final class. In other words, the class behavior cannot be changed by extending the class. This implies that one cannot override or hide any methods declared in such a class. Its methods behave as final methods (p. 226). A final class marks the lower boundary of its implementation inheritance hierarchy. A concrete class is a class that has only concrete methods—that is, methods that are non-abstract, and therefore have an implementation. Only a concrete class can be declared final. If it is decided that the class TubeLight at (12) in Example 5.9 may not be extended, it can be declared final. Any attempt to specify the class name TubeLight in an extends clause…
The continue Statement – Control Flow
4.12 The continue Statement Like the break statement, the continue statement comes in two forms: unlabeled and labeled. Click here to view code image continue; // the unlabeled formcontinuelabel; // the labeled form The continue statement can be used only in a for(;;), for(:), while, or do-while loop to prematurely stop the current iteration of the loop body and proceed with the next iteration, if possible. In the case of the while and do-while loops, the rest of the loop body is skipped—that is, the current iteration is stopped, with execution continuing with the loop condition. In the case of the for(;;) loop, the rest of the loop body is skipped, with execution continuing with the update expression. In Example 4.12, an unlabeled continue statement is used to skip an iteration in a for(;;) loop. Control is transferred to (2) when the value of i is equal to 4 at…
Overriding Instance Methods – Object-Oriented Programming
Overriding Instance Methods Under certain circumstances, a subclass can override instance methods from its superclass. Overriding such a method allows the subclass to provide its own implementation of the method. The overridden method in the superclass is not inherited by the subclass. When the method is invoked on an object of the subclass, it is the method implementation in the subclass that is executed. The new method in the subclass must abide by the following rules of method overriding: Whether parameters in the overriding method should be final is at the discretion of the subclass. A method’s signature does not comprise the final modifier of parameters, only their types and order. The criteria for overriding methods also apply to interfaces, where a subinterface can override abstract and default method declarations from its superinterfaces (p. 237). Figure 5.2 Inheritance Hierarchy for Example 5.2 The canonical examples of method overriding in Java…