OOPJ Module 3
OOPJ Module 3
BCS306A
2
OOPS with JAVA (BCS306A): Module-3 Dr Roopashree S, Dept. of CSE
Inheritance
4
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Inheritance Basics
1. To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword.
2. To see how, let’s begin with a short example.
3. The following program creates a superclass called A and a subclass called
B.
4. Notice how the keyword extends is used to create a subclass of A.
5
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Inheritance Basics
6
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Inheritance Basics
1. As you can see, the subclass B includes all of the members of its superclass,
A.
2. This is why subOb can access i and j and call showij( ).
3. Also, inside sum( ), i and j can be referred to directly, as if they were part of
B.
4. Even though A is a superclass for B, it is also a completely independent,
stand-alone class. Being a superclass for a subclass does not mean that the
superclass cannot be used by itself.
5. Further, a subclass can be a superclass for another subclass. 7
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Inheritance Basics
1. The general form of a class declaration that inherits a superclass is shown
here:
2. You can only specify one superclass for any subclass that you create.
3. Java does not support the inheritance of multiple superclasses into a
single subclass.
4. You can, as stated, create a hierarchy of inheritance in which a subclass
becomes a superclass of another subclass.
5. However, no class can be a superclass of itself 8
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Member Access and Inheritance
1. Although a subclass includes all of the members of its superclass, it cannot
access those members of the superclass that have been declared as
private.
2. The program in next slide - This program will not compile because the use
of j inside the sum( ) method of B causes an access violation.
3. Since j is declared as private, it is only accessible by other members of its
own class.
4. Subclasses have no access to it.
9
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Member Access and Inheritance
10
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
A More Practical Example
1. Here, the final version of the Box class developed in the preceding chapter
will be extended to include a fourth component called weight.
2. Thus, the new class will contain a box’s width, height, depth, and weight
11
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
A More Practical Example
12
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
A More Practical Example
13
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
A More Practical Example
1. BoxWeight inherits all of the characteristics of Box and adds to them the
weight component.
2. It is not necessary for BoxWeight to re-create all of the features found in Box.
It can simply extend Box to meet its own purposes.
3. A major advantage of inheritance is that once you have created a
superclass that defines the attributes common to a set of objects, it
can be used to create any number of more specific subclasses.
4. Each subclass can precisely tailor its own classification.
14
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
A More Practical Example
1. Remember, once you have created a superclass that defines the general
aspects of an object, that superclass can be inherited to form specialized
classes. Each subclass simply adds its own unique attributes. This is the
essence of inheritance.
15
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
A Superclass Variable Can Reference a Subclass Object
1. A reference variable of a superclass
can be assigned a reference to any
subclass derived from that
superclass
2. Here, weightbox is a reference to
BoxWeight objects, and plainbox is
a reference to Box objects.
3. Since BoxWeight is a subclass of
Box, it is permissible to assign
plainbox a reference to the
weightbox object.
16
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
A Superclass Variable Can Reference a Subclass Object
1. When a reference to a subclass object is assigned to a superclass reference variable, you
will have access only to those parts of the object defined by the superclass.
2. That is, when a reference to a subclass object is assigned to a superclass reference
variable, you will have access only to those parts of the object defined by the superclass.
3. This is why plainbox can’t access weight even when it refers to a BoxWeight object.
4. If you think about it, this makes sense, because the superclass has no knowledge of
what a subclass adds to it.
5. This is why the last line of code in the preceding fragment is commented out.
6. It is not possible for a Box reference to access the weight field, because Box does not
define one. 17
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using super
1. There will be times when you will want to create a superclass that keeps the details of its
implementation to itself (that is, that keeps its data members private).
2. In this case, there would be no way for a subclass to directly access or initialize these variables on
its own.
3. Since encapsulation is a primary attribute of OOP, it is not surprising that Java provides a solution to
this problem.
4. Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword
super.
5. super has two general forms. The first calls the superclass’ constructor.
6. The second is used to access a member of the superclass that has been hidden by a member
of a subclass
18
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using super to Call Superclass Constructors
1. A subclass can call a constructor defined by its superclass by use of the following form
of super:
2. Here, arg-list specifies any arguments needed by the constructor in the superclass.
3. super( ) must always be the first statement executed inside a subclass’ constructor
4. To see how super( ) is used, consider this improved version of the BoxWeight class:
19
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using super to Call Superclass Constructors
1. Here, BoxWeight( ) calls super( ) with the arguments w, h, and d.
2. This causes the Box constructor to be called, which initializes width, height, and depth
using these values.
3. BoxWeight no longer initializes these values itself. It only needs to initialize the value
unique to it: weight. This leaves Box free to make these values private if desired.
20
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using super to Call Superclass Constructors
1. In the preceding example, super( ) was called with three arguments.
2. Since constructors can be overloaded, super( ) can be called using any form defined by
the superclass. The constructor executed will be the one that matches the arguments.
21
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using super to Call Superclass Constructors
3. Notice that width, height, and depth have been made private within Box.
22
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using super to Call Superclass Constructors
23
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using super to Call Superclass Constructors
24
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using super to Call Superclass Constructors
25
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Review of super keyword
26
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
A Second Use for super
1. The second form of super acts somewhat like this, except that it always refers to the
superclass of the subclass in which it is used.
2. This usage has the following general form:
3. Here, member can be either a method or an instance variable.
4. This second form of super is most applicable to situations in which member names of a
subclass hide members by the same name in the superclass
5. In next example, Although the instance variable i in B hides the i in A, super allows
access to the i defined in the superclass.
27
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
A Second Use for super
28
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Creating a Multilevel Hierarchy
1. Build hierarchies that contain as many layers of inheritance as you like.
2. As mentioned, it is perfectly acceptable to use a subclass as a superclass of another.
3. For example, given three classes called A, B, and C, C can be a subclass of B, which is a
subclass of A.
4. When this type of situation occurs, each subclass inherits all of the traits found in all of its
superclasses.
5. In this case, C inherits all aspects of B and A.
6. To see how a multilevel hierarchy can be useful, consider the following program. In it, the
subclass BoxWeight is used as a superclass to create the subclass called Shipment.
7. Shipment inherits all of the traits of BoxWeight and Box, and adds a field called cost,
29
which holds the cost of shipping such a parcel
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Creating a Multilevel Hierarchy
30
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Creating a Multilevel Hierarchy
31
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Creating a Multilevel Hierarchy
1. Because of inheritance, Shipment can make use of the previously defined classes of Box
and BoxWeight, adding only the extra information it needs for its own, specific
application.
2. This is part of the value of inheritance; it allows the reuse of code.
3. This example illustrates one other important point: super( ) always refers to the
constructor in the closest superclass.
4. The super( ) in Shipment calls the constructor in BoxWeight. The super( ) in BoxWeight
calls the constructor in Box.
32
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
When Constructors Are Executed
1. When a class hierarchy is created, in what order are the constructors for the classes that
make up the hierarchy executed?
2. For example, given a subclass called B and a superclass called A, is A’s constructor
executed before B’s, or vice versa?
3. The answer is that in a class hierarchy, constructors complete their execution in order of
derivation, from superclass to subclass.
4. Further, since super( ) must be the first statement executed in a subclass’ constructor,
this order is the same whether or not super( ) is used.
5. If super( ) is not used, then the default or parameterless constructor of each superclass
will be executed.
33
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
When Constructors Are Executed
34
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Method Overriding
1. In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to
override the method in the superclass.
2. When an overridden method is called through its subclass, it will always refer to the
version of that method defined by the subclass.
35
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Method Overriding
36
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Method Overriding
1. When show( ) is invoked on an object of type B, the version of show( ) defined within B is
used.
2. That is, the version of show( ) inside B overrides the version declared in A.
3. If you wish to access the superclass version of an overridden method, you can do so by
using super.
4. For example, in this version of B, the superclass version of show( ) is invoked within the
subclass’ version.
5. This allows all instance variables to be displayed.
37
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Method Overriding
38
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Method Overriding
1. Method overriding occurs only when the names and the type signatures of the two
methods are identical.
2. If they are not, then the two methods are simply overloaded.
3. For example, consider this modified version of the preceding example:
39
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Method Overriding
40
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Method Overriding
2. This makes its type signature different from the one in A, which takes no parameters.
41
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Method Overloading vs Overriding
42
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Dynamic Method Dispatch
1. Method overriding forms the basis for one of Java’s most powerful concepts: dynamic
method dispatch.
2. Dynamic method dispatch is the mechanism by which a call to an overridden method
is resolved at run time, rather than compile time.
3. Dynamic method dispatch is important because this is how Java implements run-
time polymorphism.
4. Let’s begin by restating an important principle: a superclass reference variable can
refer to a subclass object.
5. Java uses this fact to resolve calls to overridden methods at run time.
43
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Dynamic Method Dispatch
1. Here is how. When an overridden method is called through a superclass reference, Java
determines which version of that method to execute based upon the type of the object
being referred to at the time the call occurs.
2. Thus, this determination is made at run time.
3. When different types of objects are referred to, different versions of an overridden
method will be called.
4. In other words, it is the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be executed.
5. Therefore, if a superclass contains a method that is overridden by a subclass, then when
different types of objects are referred to through a superclass reference variable, different
44
versions of the method are executed.
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Dynamic Method Dispatch
45
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Dynamic Method Dispatch
1. This program creates one superclass called A and two subclasses of it, called B and C.
2. Subclasses B and C override callme( ) declared in A. Inside the main( ) method, objects
of type A, B, and C are declared.
3. Also, a reference of type A, called r, is declared.
4. The program then in turn assigns a reference to each type of object to r and uses that
reference to invoke callme( ).
5. As the output shows, the version of callme( ) executed is determined by the type of object
being referred to at the time of the call.
6. Had it been determined by the type of the reference variable, r, you would see three calls
to A’s callme( ) method.
46
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Why Overridden Methods?
1. As stated earlier, overridden methods allow Java to support run-time polymorphism.
2. Polymorphism is essential to object-oriented programming for one reason: it allows a
general class to specify methods that will be common to all of its derivatives, while
allowing subclasses to define the specific implementation of some or all of those
methods.
3. Overridden methods are another way that Java implements the “one interface, multiple
methods” aspect of polymorphism.
4. Dynamic, run-time polymorphism is one of the most powerful mechanisms that object
oriented design brings to bear on code reuse and robustness.
5. The ability of existing code libraries to call methods on instances of new classes without
47
recompiling while maintaining a clean abstract interface is a profoundly
OOPS with JAVA (BCS306A): Module-2
Module-3
powerful
Dr Roopashree S, Dept.tool
of CSE
Applying Method Overriding
1. The following program creates a superclass called Figure that stores the dimensions of a
two-dimensional object.
2. It also defines a method called area( ) that computes the area of an object.
3. The program derives two subclasses from Figure.
4. The first is Rectangle and the second is Triangle.
5. Each of these subclasses overrides area( ) so that it returns the area of a rectangle and a
triangle, respectively
48
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Applying Method Overriding
49
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Applying Method Overriding
50
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Applying Method Overriding
51
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using Abstract Classes
1. There are situations in which you will want to define a superclass that declares the
structure of a given abstraction without providing a complete implementation of every
method.
2. That is, sometimes you will want to create a superclass that only defines a generalized
form that will be shared by all of its subclasses, leaving it to each subclass to fill in the
details.
3. Such a class determines the nature of the methods that the subclasses must implement.
4. One way this situation can occur is when a superclass is unable to create a meaningful
implementation for a method.
52
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using Abstract Classes
1. You can require that certain methods be overridden by subclasses by specifying the
abstract type modifier.
2. These methods are sometimes referred to as subclasser responsibility because they
have no implementation specified in the superclass.
3. Thus, a subclass must override them—it cannot simply use the version defined in the
superclass.
4. To declare an abstract method, use this general form:
53
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using Abstract Classes
1. As you can see, no method body is present.
2. Any class that contains one or more abstract methods must also be declared abstract.
3. To declare a class abstract, you simply use the abstract keyword in front of the class
keyword at the beginning of the class declaration.
4. There can be no objects of an abstract class. That is, an abstract class cannot be directly
instantiated with the new operator.
5. Such objects would be useless, because an abstract class is not fully defined. Also, you
cannot declare abstract constructors, or abstract static methods.
6. Any subclass of an abstract class must either implement all of the abstract methods in
the superclass, or be declared abstract itself.
54
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using Abstract Classes
55
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using Abstract Classes
1. Notice that no objects of class A are declared in the program.
2. As mentioned, it is not possible to instantiate an abstract class.
3. One other point: class A implements a concrete method called callmetoo( ).
4. This is perfectly acceptable.
5. Although abstract classes cannot be used to instantiate objects, they can be used to
create object references, because Java’s approach to run-time polymorphism is
implemented through the use of superclass references.
6. Thus, it must be possible to create a reference to an abstract class so that it can be used
to point to a subclass object.
56
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using final with Inheritance
57
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using final to Prevent Overriding
1. While method overriding is one of Java’s most powerful features, there will be times when you will
want to prevent it from occurring.
2. To disallow a method from being overridden, specify final as a modifier at the start of its declaration.
3. Methods declared as final cannot be overridden.
4. Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do
5. so, a compile-time error will result.
58
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using final to Prevent Overriding
1. Methods declared as final can sometimes provide a performance enhancement: The
compiler is free to inline calls to them because it “knows” they will not be overridden by a
subclass.
2. When a small final method is called, often the Java compiler can copy the bytecode for
the subroutine directly inline with the compiled code of the calling method, thus
eliminating the costly overhead associated with a method call.
3. Inlining is an option only with final methods.
4. Normally, Java resolves calls to methods dynamically, at run time.
5. This is called late binding.
6. However, since final methods cannot be overridden, a call to one can be resolved at
59
compile time. This is called early binding.
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Using final to Prevent Inheritance
1. Sometimes you will want to prevent a class from being inherited.
2. To do this, precede the class declaration with final.
3. Declaring a class as final implicitly declares all of its methods as final, too.
4. As you might expect, it is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its subclasses to provide complete
implementations.
60
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
The Object Class
1. There is one special class, Object, defined by Java. All other classes are subclasses of
Object.
2. That is, Object is a superclass of all other classes. This means that a reference variable
of type Object can refer to an object of any other class.
3. Also, since arrays are implemented as classes, a variable of type Object can also refer to
any array.
4. Object defines the following methods, which means that they are available in every object
61
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
The Object Class
62
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
The Object Class
1. The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final.
2. You may override the others.
3. However, notice two methods now: equals( ) and toString( ). The equals( ) method
compares two objects.
4. It returns true if the objects are equal, and false otherwise.
5. The precise definition of equality can vary, depending on the type of objects being
compared.
6. The toString( ) method returns a string that contains a description of the object on which
it is called.
7. Also, this method is automatically called when an object is output using println( ).
63
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Interfaces
1. Using the keyword interface, you can fully abstract a class’ interface from its
implementation.
2. That is, using interface, you can specify what a class must do, but not how it does it.
3. Interfaces are syntactically similar to classes, but they lack instance variables, and, as a
general rule, their methods are declared without any body.
4. In practice, this means that you can define interfaces that don’t make assumptions about
how they are implemented.
5. Once it is defined, any number of classes can implement an interface. Also, one class
can implement any number of interfaces.
64
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Interfaces
1. To implement an interface, a class must provide the complete set of methods required by
the interface.
2. However, each class is free to determine the details of its own implementation.
3. By providing the interface keyword, Java allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism.
4. Interfaces are designed to support dynamic method resolution at run time.
65
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Defining an Interface
1. An interface is defined much like a class. This is a simplified general form of an interface:
66
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Defining an Interface
1. When no access modifier is included, then default access results, and the interface is
only available to other members of the package in which it is declared.
2. When it is declared as public, the interface can be used by code outside its package.
3. In this case, the interface must be the only public interface declared in the file, and the
file must have the same name as the interface. name is the name of the interface, and
can be any valid identifier.
4. Notice that the methods that are declared have no bodies.
5. They end with a semicolon after the parameter list.
6. They are, essentially, abstract methods. Each class that includes such an interface must
implement all of the methods. 67
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Defining an Interface
1. As the general form shows, variables can be declared inside interface declarations.
2. They are implicitly final and static, meaning they cannot be changed by the implementing
class.
3. They must also be initialized. All methods and variables are implicitly public.
4. Here is an example of an interface definition. It declares a simple interface that contains
one method called callback( ) that takes a single integer parameter
68
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Implementing Interfaces
1. Once an interface has been defined, one or more classes can implement that interface.
2. To implement an interface, include the implements clause in a class definition, and then
create the methods required by the interface.
3. The general form of a class that includes the implements clause looks like this:
69
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Implementing Interfaces
1. If a class implements more than one interface, the interfaces are separated with a comma.
2. If a class implements two interfaces that declare the same method, then the same method will be
used by clients of either interface.
3. The methods that implement an interface must be declared public.
4. Also, the type signature of the implementing method must match exactly the type signature specified
in the interface definition.
70
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Implementing Interfaces
1. It is both permissible and common for classes that implement interfaces to define additional members
of their own.
2. For example, the following version of Client implements callback( ) and adds the method
nonIfaceMeth( ):
71
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Accessing Implementations Through Interface References
1. You can declare variables as object references that use an interface rather than a class type.
2. Any instance of any class that implements the declared interface can be referred to by such a
variable.
3. When you call a method through one of these references, the correct version will be called based on
the actual instance of the interface being referred to.
4. This is one of the key features of interfaces. The method to be executed is looked up dynamically at
run time, allowing classes to be created later than the code which calls methods on them.
5. The calling code can dispatch through an interface without having to know anything about the
“callee.”
72
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Accessing Implementations Through Interface References
1. Notice that variable c is declared to be of the interface type Callback, yet it was assigned an instance
of Client.
2. Although c can be used to access the callback( ) method, it cannot access any other members of the
Client class. An interface reference variable has knowledge only of the methods declared by its
interface declaration. Thus, c could not be used to access nonIfaceMeth( ) since it is defined by
73
Client but not Callback. Dr Roopashree S, Dept. of CSE
OOPS with JAVA (BCS306A): Module-2
Module-3
Accessing Implementations Through Interface References
1. While the preceding example shows, mechanically, how an interface reference variable
can access an implementation object, it does not demonstrate the polymorphic power of
such a reference.
2. To sample this usage, first create the second implementation of Callback, shown here:
74
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Partial Implementations
1. If a class includes an interface but does not fully implement the methods required by that
interface, then that class must be declared as abstract. For example:
2. Here, the class Incomplete does not implement callback( ) and must be declared as
abstract.
3. Any class that inherits Incomplete must implement callback( ) or be declared abstract
itself. 75
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Nested Interfaces
1. An interface can be declared a member of a class or another interface.
2. Such an interface is called a member interface or a nested interface.
3. A nested interface can be declared as public, private, or protected. This differs from a
top-level interface, which must either be declared as public or use the default access
level, as previously described.
4. When a nested interface is used outside of its enclosing scope, it must be qualified by
the name of the class or interface of which it is a member.
5. Thus, outside of the class or interface in which a nested interface is declared, its name
must be fully qualified
76
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Nested Interfaces
77
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Nested Interfaces
1. Notice that A defines a member interface called NestedIF and that it is declared public.
2. Next, B implements the nested interface by specifying
3. Notice that the name is fully qualified by the enclosing class’ name.
4. Inside the main( ) method, an A.NestedIF reference called nif is created, and it is
assigned a reference to a B object.
5. Because B implements A.NestedIF, this is legal
78
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Applying Interfaces
1. Initially we have developed a class called Stack that implemented a simple fixed-size
stack.
2. However, there are many ways to implement a stack. For example, the stack can be of a
fixed size or it can be “growable.”
3. The stack can also be held in an array, a linked list, a binary tree, and so on. No matter
how the stack is implemented, the interface to the stack remains the same.
4. That is, the methods push( ) and pop( ) define the interface to the stack independently of
the details of the implementation.
5. Because the interface to a stack is separate from its implementation, it is easy to define a
stack interface, leaving it to each implementation to define the specifics. 79
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Applying Interfaces
1. First, here is the interface that defines an integer stack.
2. Put this in a file called IntStack.java.
3. This interface will be used by both stack implementations.
4. The following program creates a class called FixedStack that implements a fixed-length
version of an integer stack:
80
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Applying Interfaces
81
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Applying Interfaces
82
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Applying Interfaces
83
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Applying Interfaces
1. The following class uses both the FixedStack and DynStack implementations.
2. It does so through an interface reference.
3. This means that calls to push( ) and pop( ) are resolved at run time rather than at compile
time.
4. In this program, mystack is a reference to the IntStack interface. Thus, when it refers to
ds, it uses the versions of push( ) and pop( ) defined by the DynStack implementation.
5. When it refers to fs, it uses the versions of push( ) and pop( ) defined by FixedStack. As
explained, these determinations are made at run time.
6. Accessing multiple implementations of an interface through an interface reference
variable is the most powerful way that Java achieves run-time polymorphism. 84
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Applying Interfaces
85
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Default Interface Methods
1. The release of JDK 8 changed this by adding a new capability to interface called the
default method.
2. A default method lets you define a default implementation for an interface method. In
other words, by use of a default method, it is possible for an interface method to provide
a body, rather than being abstract.
3. During its development, the default method was also referred to as an extension method
86
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Default Interface Methods
1. A primary motivation for the default method was to provide a means by which interfaces
could be expanded without breaking existing code.
2. Recall that there must be implementations for all methods defined by an interface. In the
past, if a new method were added to a popular, widely used interface, then the addition of
that method would break existing code because no implementation would be found for
that new method.
3. The default method solves this problem by supplying an implementation that will be used
if no other implementation is explicitly provided.
4. Thus, the addition of a default method will not cause preexisting code to break.
5. Another motivation for the default method was the desire to specify methods in an
87
interface that are, essentially, optional, depending on how the interface
OOPS with JAVA (BCS306A): Module-2
Module-3
is used.
Dr Roopashree S, Dept. of CSE
Default Interface Methods
1. It is important to point out that the addition of default methods does not change a key
aspect of interface: its inability to maintain state information. An interface still cannot have
instance variables, for example.
2. Thus, the defining difference between an interface and a class is that a class can
maintain state information, but an interface cannot.
3. Furthermore, it is still not possible to create an instance of an interface by itself. It must
be implemented by a class.
4. Therefore, even though, beginning with JDK 8, an interface can define default methods,
the interface must still be implemented by a class if an instance is to be created
88
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Default Method Fundamentals
1. An interface default method is defined similar to the way a method is defined by a class.
2. The primary difference is that the declaration is preceded by the keyword default.
89
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Default Method Fundamentals
1. MyIF declares two methods. The first, getNumber( ), is a standard interface method
declaration.
2. It defines no implementation whatsoever.
3. The second method is getString( ), and it does include a default implementation. In this
case, it simply returns the string "Default String".
4. Pay special attention to the way getString( ) is declared.
5. Its declaration is preceded by the default modifier. This syntax can be generalized.
6. To define a default method, precede its declaration with default.
90
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Default Method Fundamentals
1. Because getString( ) includes a default implementation, it is not necessary for an
implementing class to override it.
2. In other words, if an implementing class does not provide its own implementation, the
default is used.
3. For example, the MyIFImp class shown next is perfectly valid.
91
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Default Method Fundamentals
1. The following code creates an instance of MyIFImp and uses it to call both getNumber( )
and getString( ).
92
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Default Method Fundamentals
1. As you can see, the default implementation of getString( ) was automatically used.
2. It was not necessary for MyIFImp to define it.
3. Thus, for getString( ), implementation by a class is optional. (Of course, its
implementation by a class will be required if the class uses getString( ) for some purpose
beyond that supported by its default.)
4. It is both possible and common for an implementing class to define its own
implementation of a default method.
5. For example, MyIFImp2 overrides getString( ):
93
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Default Method Fundamentals
94
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Multiple Inheritance Issues
1. Java does not support the multiple inheritance of classes.
2. Now that an interface can include default methods, you might be wondering if an
interface can provide a way around this restriction.
3. The answer is, essentially, no. Recall that there is still a key difference between a class
and an interface: a class can maintain state information (especially through the use of
instance variables), but an interface cannot.
95
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Use static Methods in an Interface
1. Another capability added to interface by JDK 8 is the ability to define one or more static
methods.
2. Like static methods in a class, a static method defined by an interface can be called
independently of any object.
3. Thus, no implementation of the interface is necessary, and no instance of the interface is
required, in order to call a static method.
4. Instead, a static method is called by specifying the interface name, followed by a period,
followed by the method name.
5. Here is the general form:
96
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Use static Methods in an Interface
1. The following shows an example of a static method in an interface by adding one to MyIF,
shown in the previous section. The static method is getDefaultNumber( ). It returns zero
97
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Use static Methods in an Interface
1. As mentioned, no implementation or instance of MyIF is required to call
getDefaultNumber( ) because it is static.
2. One last point: static interface methods are not inherited by either an implementing class
or a subinterface
98
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Private Interface Methods
1. Beginning with JDK 9, an interface can include a private method. A private interface
method can be called only by a default method or another private method defined by the
same interface.
2. Because a private interface method is specified private, it cannot be used by code
outside the interface in which it is defined.
3. This restriction includes subinterfaces because a private interface method is not inherited
by a subinterface.
4. The key benefit of a private interface method is that it lets two or more default methods
use a common piece of code, thus avoiding code duplication.
99
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Private Interface Methods
1. For example, here is another version of the IntStack interface that has two default
methods called popNElements( ) and skipAndPopNElements( ).
2. The first returns an array that contains the top N elements on the stack.
3. The second skips a specified number of elements and then returns an array that contains
the next N elements.
4. Both use a private method called getElements( ) to obtain an array of the specified
number of elements from the stack.
100
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Private Interface Methods
101
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
Private Interface Methods
1. Notice that both popNElements( ) and skipAndPopNElements( ) use the private
getElements( ) method to obtain the array to return.
2. This prevents both methods from having to duplicate the same code sequence.
3. Keep in mind that because getElements( ) is private, it cannot be called by code outside
IntStack.
4. Thus, its use is limited to the default methods inside IntStack. Also, because
getElements( ) uses the pop( ) method to obtain stack elements, it will automatically call
the implementation of pop( ) provided by the IntStack implementation.
5. Thus, getElements( ) will work for any stack class that implements IntStack.
102
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE
End of Module 03
103
OOPS with JAVA (BCS306A): Module-2
Module-3 Dr Roopashree S, Dept. of CSE