Author Archives: Linda Hammock

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

Abstract Methods in Interfaces An interface defines a contract by specifying a set of abstract and default method declarations, but provides implementations only for the default methods—not for the abstract methods. The abstract methods in an interface are all implicitly abstract and public by virtue of their definitions. Only the modifiers abstract and public are allowed, but these are invariably omitted. An abstract method declaration has the following simple form in a top-level interface: Click here to view code image return_type method_name (formal_parameter_list)throws_clause; An abstract method declaration is essentially a method header terminated by a semicolon (;). Note that an abstract method is an instance method whose implementation will be provided by a class that implements the interface in which the abstract method is declared. The throws clause is discussed in §7.5, p. 388. The interface Playable shown below declares an abstract method play(). This method is implicitly declared to be…

Read more

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…

Read more

Extending Interfaces An interface can extend other interfaces, using the extends clause. Unlike when extending classes, an interface can extend several interfaces. The interfaces extended by an interface (directly or indirectly) are called superinterfaces. Conversely, the interface is a subinterface of its superinterfaces. Since interfaces define new reference types, superinterfaces and subinterfaces are also supertypes and subtypes, respectively. A subinterface inherits from its superinterfaces all members of those superinterfaces, except for the following: Barring any conflicts, a subinterface inherits abstract and default method declarations that are not overridden, as well as constants and static member types that it does not hide in its superinterfaces. In addition, abstract, static, and default method declarations can be overloaded, analogous to method overloading in classes. For a detailed discussion of overriding abstract methods from multiple superinterfaces, see §11.12, p. 621. Example 5.10 illustrates the relationships between classes and interfaces. In Example 5.10, the interface…

Read more

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…

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

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 { } //…

Read more

5.2 The Object Reference super The this reference can be used in non-static code to refer to the current object (§3.5, p. 106). The keyword super, in contrast, can be used in non-static code to access fields and invoke methods from the superclass. The keyword super provides a reference to the current object as an instance of its superclass. In method invocations with super, the method from the superclass is invoked regardless of what the actual type of the current object is or whether the current class overrides the method. This approach is typically used to invoke methods that are overridden and to access members that are hidden to the subclass. Unlike the this keyword, the super keyword cannot be used as an ordinary reference. For example, it cannot be assigned to other references or cast to other reference types. Example 5.4 uses the superclass Light and its subclass TubeLight…

Read more

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 …

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

10/30