Category Archives: The Object Reference super

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…

Read more

Overriding Default Methods Overriding a default method from an interface does not necessarily imply that a new implementation is being provided. The default method can also be overridden by providing an abstract method declaration, as illustrated by the code below. The default method printSlogan() at (1) in the interface ISlogan is overridden by an abstract method declaration at (2) and (3) in the interface INewSlogan and the abstract class JavaMaster, respectively. This strategy effectively forces the subtypes of the interface INewSlogan and of the abstract class JavaMaster to provide a new concrete implementation for the method, as one would expect for an abstract method. Click here to view code image interface ISlogan {  default void printSlogan() {         // (1) Default method.    System.out.println(“Happiness is getting certified!”);  }}interface INewSlogan extends ISlogan {  @Override  abstract void printSlogan();         // (2) overrides (1) with abstract method.}abstract class JavaMaster implements ISlogan {  @Override  public abstract void…

Read more

5.4 Abstract Classes and Methods The keyword abstract is used in the following contexts in Java: Abstract Classes A concrete class is one that defines, by virtue of its public methods, a contract for services it guarantees its clients and provides the implementation for all the methods necessary to fulfill that contract. Clients can readily instantiate a concrete class and use its objects. In certain cases, a class might want to define the contract for the services, but only provide partial implementation for its contract. Such a design decision might be necessary if the abstraction the class represents is so general that certain aspects need to be specialized by subclasses to be of practical use, but at the same time guarantee that these will be implemented by the subclasses. This design strategy can be implemented by using abstract classes. Clients cannot instantiate an abstract class, but now its concrete subclasses…

Read more

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…

Read more

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

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…

Read more

4.9 Transfer Statements Java provides the following language constructs for transferring control in a program: The throw statement can also transfer control in a program (§7.4, p. 386). 4.10 Labeled Statements A statement may have a label: label :statement A label is any valid identifier; it always immediately precedes the statement. Label names exist in their own namespace, so that they do not conflict with names of packages, classes, interfaces, methods, fields, and local variables. The scope of a label is the statement prefixed by the label, meaning that it cannot be redeclared as a label inside the labeled statement—analogous to the scope of local variables. Click here to view code image L1: if (i > 0) {  L1: System.out.println(i);    // (1) Not OK. Label L1 redeclared.}L1: while (i < 0) {             // (2) OK.  L2: System.out.println(i);}L1: {                           // (3) OK. Labeled block.  int j = 10;  System.out.println(j);}L1: try {                       //…

Read more

The Subtype–Supertype Relationship A class defines a reference type, a data type whose objects can be accessed only by references. Therefore, the inheritance hierarchy can be regarded as a type hierarchy, embodying the subtype–supertype relationship between reference types. The subclass– superclass relationship is a special case of the subtype–supertype relationship that is between classes. The subclass–superclass relationship allows single inheritance of type, meaning that the subclass inherits the type of its direct superclass. This is in contrast to a class that implements several interfaces, resulting in multiple inheritance of type—that is, a class inherits the type of all interfaces it implements. In the context of Java, the subtype–supertype relationship implies that the reference value of a subtype object can be assigned to a supertype reference because a subtype object can be substituted for a supertype object. This assignment involves a widening reference conversion, as references are assigned up the inheritance…

Read more

4.13 The return Statement The return statement is used to stop execution of a method (or a constructor) and transfer control back to the calling code (also called the caller or invoker). The usage of the two forms of the return statement is dictated by whether that statement is used in a void or a non-void method (Table 4.2). The first form does not return any value to the calling code, but the second form does. Note that the keyword void does not represent any type. In Table 4.2, the expression must evaluate to a primitive value or a reference value, and its type must be assignable to the return type specified in the method header (§2.7, p. 54, and §5.9, p. 261). See also the discussion on covariant return in connection with method overriding in §5.1, p. 201. As can be seen from Table 4.2, a void method need…

Read more

10/10