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…
Abstract Methods in Interfaces – Object-Oriented Programming
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…
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 { } //…
The Object Reference super – Object-Oriented Programming
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…
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 …
Abstract Classes and Methods – Object-Oriented Programming
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…
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…
Definite Assignment Analysis for Final Variables – Object-Oriented Programming
Definite Assignment Analysis for Final Variables The name of a final variable can occur in the following contexts: in its declaration when it is declared, in the context of an assignment when it is assigned a value, and in the context where its value is accessed in an expression. The analysis performed by the compiler determines whether the blank final variable is initialized before its value is accessed. This involves checking whether a blank final variable has been assigned a value on any possible path of execution to where the value of the variable is accessed. In technical terms, this means a blank final variable must be definitely assigned before any access. Click here to view code image final int k; // Declaration: blank final local variablek = 10; // (1) AssignmentSystem.out.println(k); // (2) Access: k is definitely assigned. boolean status = true; // Non-constant variable.final int j; // Declaration:…
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…
Relationships: is-a and has-a – Object-Oriented Programming
Relationships: is-a and has-a The inheritance relationship between a subclass and its superclass is embodied by the is-a relationship. Since a subclass inherits from its superclass, a subclass object is-a superclass object, and can be used wherever an object of the superclass can be used. It has particular consequences for how objects can be used. An object of the TubeLight class is-an object of the superclass Light. Referring to Figure 5.1, an object of the TubeLight class can be used wherever an object of the superclass Light can be used. The inheritance relationship is transitive: If class B extends class A and class C extends class B, then class C will also inherit from class A via class B. In Figure 5.1, an object of the SpotLightBulb class is-an object of the class Light. The is-a relationship does not hold between peer classes: An object of the LightBulb class is…