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…
Default Methods in Interfaces – Object-Oriented Programming
Default Methods in Interfaces Only interfaces can define default methods. A default method is an instance method declared with the keyword default and whose implementation is provided by the interface. However, a default method in a top-level interface always has public access, whether the keyword public is specified or not. Click here to view code image defaultreturn_type method_name (formal_parameter_list)throws_clause {implementaion_of_method_body } A class implementing an interface can optionally decide to override any default method in the interface, as can a subinterface of the interface. If a default method is not overridden to provide a new implementation, the default implementation provided by the interface is inherited by the class or the subinterface. No other non-access modifiers, such as abstract, final, or static, are allowed in a default method declaration. A default method is not abstract because it provides an implementation; is not final because it can be overridden; and is not static because…
Chaining Constructors Using this() and super() – Object-Oriented Programming
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 …
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()…
Abstract Methods in Classes – Object-Oriented Programming
Abstract Methods in Classes In this subsection we discuss in more detail declaring and overriding abstract methods in classes. Declaring an abstract Method An abstract method in an abstract class has the following syntax: Click here to view code image access_modifier abstractreturn_type method_name (formal_parameter_list) throws_clause; An abstract method does not have an implementation; that is, no method body is defined for an abstract method, and only the method header is provided in the class declaration. The keyword abstract is mandatory in the header of an abstract method declared in a class. Its class is then incomplete and must be explicitly declared as abstract. Subclasses of an abstract class must then override the abstract method to provide the method implementation; otherwise, they must also be declared as abstract. Overriding an abstract Method When overriding an abstract method from the superclass, the notation @Override should always be used in the overriding method in the subclass.…
Extending an abstract Class – Object-Oriented Programming
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; …
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…
Hiding Static Methods – Object-Oriented Programming
Hiding Static Methods Only instance methods in an object can be overridden. However, a static method in a subclass can hide a static method from the superclass. Hiding a static method is analogous to overriding an instance method except for one important aspect: Calls to static methods are bound at compile time as opposed to runtime for calls to overridden instance methods, and therefore do not exhibit polymorphic behavior exhibited by calls to overridden instance methods (p. 278). When hiding a static method, the compiler will flag an error if the signatures are the same, but the other requirements regarding the return type, throws clause, and accessibility are not met. If the signatures are different, the method name is overloaded, not hidden. A static method in the subclass can only hide a static method in the superclass. Analogous to an overridden instance method, a hidden superclass static method is not…
Implementing Inheritance – Object-Oriented Programming
5.1 Implementing Inheritance Inheritance is one of the fundamental mechanisms for code reuse in OOP. It allows new classes to be derived from existing ones. The new class (also called a subclass, subtype, derived class, or child class) can inherit members from the old class (also called a superclass, supertype, base class, or parent class). The subclass can add new behavior and properties and, under certain circumstances, modify its inherited behavior. A subclass specifies the name of its superclass in the subclass header using the extends clause. Click here to view code image class TubeLight extends Light { … } // TubeLight is a subclass of Light. The subclass specifies only the additional new and modified members in its class body. The rest of its declaration is made up of its inherited members. If no extends clause is specified in the header of a class declaration, the class implicitly inherits…
Covariant return in Overriding Methods – Object-Oriented Programming
Covariant return in Overriding Methods In Example 5.2, the definition of the method makeInstance() at (9) overrides the method definition at (3). Click here to view code image // The overridden method in the superclass Light:public Light makeInstance() { … } // (3) Instance method // The overriding method in the subclass TubeLight:@Overridepublic TubeLight makeInstance() { … } // (9) Overriding instance method at (3). Note that the method signatures are the same, but the return type at (9) is a subtype of the return type at (3). The method at (9) returns an object of the subtype Tube-Light, whereas the method at (3) returns an object of the supertype Light. This is an example of covariant return. Depending on whether we call the method makeInstance() on an object of the subtype TubeLight or an object of the supertype Light, the respective method definition will be executed. The code at…