Object Oriented Programming with JAVA Module-3
Module -3
Chapter1: Inheritance
• In object-oriented programming, inheritance is a fundamental concept that enables the
creation of hierarchical classifications.
• It involves the creation of a general class (superclass) defining common traits for a group
of related items. Other, more specific classes (subclasses) can then inherit from this
superclass, adding unique elements while retaining the inherited traits.
• In Java terminology, the inherited class is the superclass, and the inheriting class is the
subclass.
1. Inheritance Basics
To inherit a class, you simply incorporate one class into another by using the extends keyword.
• The general form of a class declaration that inherits:
class subclass-name extends superclass-name {
// body of class
}
The following program creates a superclass called A and a subclass called B (simple/single
inheritance).
// Create a superclass.
class A
{
int i;
void showi( )
{
[Link]("i is: " + i );
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void sum()
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 1 | 28
Object Oriented Programming with JAVA Module-3
{
[Link]("i+k: " + (i+k));
}
}
class SimpleInheritance
{
public static void main(String[ ] args) {
B s1= new B( );
s1.i = 10;
[Link]("Contents of superOb: "+ [Link]( ));
s1.k = 9;
[Link]("Contents of subOb: "+[Link]( ));
}
}
The output from this program is shown here:
Contents of superob: i is :10
Contents of subOb: (i+k):16
• Here, The subclass B includes all of the members of its superclass, A. This is why sub
can access i and call showi( ). Also, inside sum( ), i can be referred to directly, as if
they were part of B.
• 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. Further, a subclass can be a superclass for another subclass (multi-level
inheritance).
1.1 Member Access and Inheritance
• 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.
• For example, consider the following simple class hierarchy:
class A {
int i; // default access
private int j; // private to A
void setij(int x, int y) {
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 2 | 28
Object Oriented Programming with JAVA Module-3
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A {
int total;
void sum( ) {
total = i + j; // ERROR, j is not accessible here
}
}
class Access {
public static void main(String[] args) {
B subOb = new B();
[Link](10, 12);
[Link]();
[Link]("Total is " + [Link]);
}
}
Output: Error or program can’t compile.
1.2 A More Practical Example
• Here, the final version of the Box class will be extended to include a fourth component
called weight. Thus, the new class will contain a box’s width, height, depth, and weight.
// This program uses inheritance to extend Box.
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 3 | 28
Object Oriented Programming with JAVA Module-3
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
// Box is extended to include weight.
class BoxWeight extends Box
{
double weight; // weight of box
// constructor for BoxWeight
BoxWeight(double w, double h, double d, double m)
{
width = w;
height = h;
depth = d;
weight = m;
}
}
class DemoBoxWeight {
public static void main(String[] args) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
double vol = [Link]();
[Link]("Volume of mybox1 is " + vol);
[Link]("Weight of mybox1 is " + [Link]);
}}
The output from this program is shown here:
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 4 | 28
Object Oriented Programming with JAVA Module-3
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
2. Using super
• In Java, the super keyword is used to refer to the immediate parent class object.
• super has two general forms.
o The first calls the superclass constructor.
o The second is used to access a member of the superclass that has been hidden by a
member of a subclass.
2.1 Using super to Call Superclass Constructors
• A subclass can call a constructor defined by its superclass by use of the following form of
super: super(arg-list);
• Here, arg-list specifies any arguments needed by the constructor in the superclass. super(
) must always be the first statement executed inside a subclass’ constructor.
// Example: Am Implementation of BoxWeight.
class Box
{
private double width;
private double height;
private double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double vol()
{
return width*height*depth;
}
}
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 5 | 28
Object Oriented Programming with JAVA Module-3
// BoxWeight now fully implements all constructors.
class BoxWeight extends Box
{
double weight; // weight of box
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m)
{
super(w, h, d); // call superclass constructor
weight = m;
}
}
class DemoSuper {
public static void main(String[ ] args) {
BoxWeight box1 = new BoxWeight(10, 20, 15, 34.3);
[Link]("Volume of box1 is " +box1. Vol( ));
[Link]("Weight of box1 is " + [Link]);
}
}
This program generates the following output:
Volume of box1 is 3000.0
Weight of box1 is 34.3
2.2 A Second Use for super
• It always refers to the superclass of the subclass in which it is used.
• This usage has the following general form:
[Link]; // Here, member can be either a method or an instance variable.
• 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.
• Consider this simple class hierarchy:
// Using super to overcome name hiding.
class A {
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 6 | 28
Object Oriented Programming with JAVA Module-3
int i;
}
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
[Link]("i in superclass: " + super.i);
[Link]("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String[] args) {
B subOb = new B(1, 2);
[Link]();
}
}
Output:
i in superclass: 1
i in subclass: 2
3. Creating a Multilevel Hierarchy
• Given three classes called A, B, and C, C can be a subclass of B, which is a subclass of A. In
this case, C inherits all aspects of B and A.
• Consider the following program. In it, the subclass BoxWeight is used as a superclass to create
the subclass called Shipment.
• Shipment inherits all of the traits of BoxWeight and Box, and adds a field called cost, which
holds the cost of shipping such a parcel.
class Box {
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 7 | 28
Object Oriented Programming with JAVA Module-3
private double width;
private double height;
private double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume( ) {
return width * height * depth;
}
}
// Add weight.
class BoxWeight extends Box {
double weight; // weight of box
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
// Add shipping costs.
class Shipment extends BoxWeight {
double cost;
Shipment(double w, double h, double d, double m, double c) {
super(w, h, d, m); // call superclass constructor
cost = c;
}
class DemoShipment {
public static void main(String[ ] args) {
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 8 | 28
Object Oriented Programming with JAVA Module-3
Shipment s = new Shipment(10, 20, 15, 10, 3.41);
double vol = [Link]( );
[Link]("Volume of shipment1 is " + vol);
[Link]("Weight of shipment1 is " + [Link]);
[Link]("Shipping cost: $" + [Link]);
}
}
The output of this program is shown here:
Volume of shipmen t1 is 3000.0
Weight of shipment1 is 10.0
Shipping cost: $3.41
4. When Constructors Are Executed
• Given a subclass called B and a superclass called A, in a class hierarchy, constructors complete
their execution in order of derivation, from superclass to subclass.
• Further, since super( ) must be the first statement executed in a subclass’ constructor, this order
is the same whether or not super( ) is used. If super( ) is not used, then the default or parameter
less constructor of each superclass will be executed.
• The following program illustrates when constructors are executed:
// Create a super class.
class A {
A( ) {
[Link]("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B( ) {
[Link]("Inside B's constructor.");
}
}
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 9 | 28
Object Oriented Programming with JAVA Module-3
// Create another subclass by extending B.
class C extends B {
C( ) {
[Link]("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String[ ] args) {
C c = new C( );
}
}
• The output from this program is shown here:
Inside A's constructor
Inside B's constructor
Inside C's constructor
5. Method Overriding
• Method overriding occurs when a subclass provides a specific implementation for a
method that is already defined in its superclass then the method in the subclass is said to
override the method in the superclass.
• Conditions for Method Overriding: Same method name, Same method type signature
(parameters and return type).
• When an overridden method is called from within its subclass, it will always refer to the
version of that method defined by the subclass.
• The version of the method defined by the superclass will be hidden.
• Consider the following example:
class A
{
int i;
A(int a) {
i = a;
}
void show( ) {
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 10 | 28
Object Oriented Programming with JAVA Module-3
[Link]("i is: " + i );
}
}
class B extends A {
int k;
B(int a, int c) {
super(a);
k = c;
}
// display k – this overrides show() in A
void show() {
[Link]("k: " + k);
}
}
class Override {
public static void main(String[] args) {
B subOb = new B(1, 3);
[Link](); // this calls show() in B
}
}
• The output produced by this program is shown here:
k: 3
• When show( ) is invoked on an object of type B, the version of show( ) defined within B
is used. That is, the version of show( ) inside B overrides the version declared in A.
• To access the superclass version of an overridden method, super will be used.
• Method overriding occurs only when the names and the type signatures of the two
methods are identical. If they are not, then the two methods are simply overloaded.
6. Dynamic Method Dispatch
Method overriding in Java forms the foundation for dynamic method dispatch.
“Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.”
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 11 | 28
Object Oriented Programming with JAVA Module-3
Dynamic method dispatch is crucial for achieving run-time polymorphism in Java.
A superclass reference variable can refer to a subclass object.
When an overridden method is called through a superclass reference, Java determines the version
to execute based on the type of the object being referred to at run time.
It is the type of the object (not the type of the reference variable) that determines which version of
an overridden method will be executed.
Different versions of an overridden method are called when different types of objects are referred
to through a superclass reference variable.
Example: Dynamic Method Dispatch
class A {
void callme( )
{
[Link]("Inside A's callme method");
}}
class B extends A {
// override callme( )
void callme( ) {
[Link]("Inside B's callme method");
}}
class Dispatch {
public static void main(String[ ] args) {
A a = new A( ); // object of type A
B b = new B( ); // object of type B
A r; // obtain a reference of type A
r = a; // r refers to an A object
[Link](); // calls A's version of callme
r = b; // r refers to a B object
[Link](); //
calls B's version of callme
}
}
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 12 | 28
Object Oriented Programming with JAVA Module-3
The output from the program is shown here:
Inside A's callme method
Inside B's callme method
7. Using Abstract Classes
Java abstract class is a class that can not be initiated by itself, it needs to be subclassed
by another class to use its properties.
An abstract class is declared using the “abstract” keyword in its class definition.
The main purpose of an abstract class is to provide a common structure for its subclasses,
ensuring that they implement certain essential methods.
An abstract class can also have constructors, data members, and static methods
To declare an abstract method, use this general form:
abstract type name(parameter-list);
Using an abstract class, you can improve the Figure class. Since there is no meaningful
concept of area for an undefined two-dimensional figure, the following version of the
program declares area( ) as abstract inside Figure. This, of course, means that all classes
derived from Figure must override area( ).
// Using abstract methods and classes.
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 13 | 28
Object Oriented Programming with JAVA Module-3
// override area for rectangle
double area() {
[Link]("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class AbstractAreas {
public static void main(String[ ] args) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Figure figref; // this is OK, no object is created
figref = r;
[Link]("Area is " + [Link]());
}}
As the comment inside main( ) indicates, it is no longer possible to declare objects of type
Figure, since it is now abstract. And, all subclasses of Figure must override area( ). To
prove this to yourself, try creating a subclass that does not override area( ). You will receive
a compile-time error. Although it is not possible to create an object of type Figure, you can
create a reference variable of type Figure. The variable figref is declared as a reference to
Figure, which means that it can be used to refer to an object of any class derived from
Figure. As explained, it is through superclass reference variables that overridden methods
are resolved at run time.
8. Using final with Inheritance
The keyword final has two uses. The uses of final apply to inheritance.
8.1 Using final to Prevent Overriding
While method overriding is one of Java’s most powerful features, there will be times when
you will want to prevent it from occurring. To disallow a method from being overridden,
specify final as a modifier at the start of its declaration. Methods declared as final cannot
be overridden. The following fragment illustrates final:
class A {
final void meth( ) {
[Link]("This is a final method.");
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 14 | 28
Object Oriented Programming with JAVA Module-3
}
}
class B extends A {
void meth( ) { // ERROR! Can't override.
[Link]("Illegal!");
}}
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do
so, a compile-time error will result.
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.
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.
8.2 Using final to Prevent Inheritance
Sometimes you will want to prevent a class from being inherited. To do this, precede the
class declaration with final. Declaring a class as final implicitly declares all of its methods
as final, too. 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.
Here is an example of a final class:
final class A {
//...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
//...
}
9. Local Variable Type Inference and Inheritance
• Local variable type inference to the Java language, which is supported by the
context-sensitivekeyword var.
• A superclass reference can refer to a derived class object, and this feature is part of
Java’s support for polymorphism.
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 15 | 28
Object Oriented Programming with JAVA Module-3
• However, it is critical to remember that, when using local variable type inference,
the inferred type of a variable is based on the declared type of its initializer.
• Therefore, if the initializer is of the super classtype, that will be the inferred type of
the variable.
• It does not matter if the actual object being referred to by the initializer is an
instance of a derived class. For example, consider the following program:
class Vehicle
void startEngine( )
[Link]("Vehicle engine starting.");
}}
class Car extends Vehicle
void drive( ) {
[Link](“Driving car");
}}
public class InferenceDemo {
public static void main(String[ ] args)
var c1 = new Car();
[Link]();
[Link]();
}}
10. The Object Class
There is one special class, Object, defined by Java. All other classes are subclasses of
Object. 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.
Also, since arrays are implemented as classes, a variable of type Object can also refer to
any array.
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 16 | 28
Object Oriented Programming with JAVA Module-3
The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final.
equals( ) and toString( ). The equals( ) method compares two objects.
It returns true if the objects are equal, and false otherwise.
The precise definition of equality can vary, depending on the type of objects being compared.
The toString( ) method returns a string that contains a description of the object on which it
is called. Also, this method is automatically called when an object is output using println( ).
Many classes override this method. Doing so allows them to tailor a description
specifically for the types of objects that they create.
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 17 | 28
Object Oriented Programming with JAVA Module-3
Chapter 2: Interfaces
1. Interfaces
o Using the keyword interface, user can fully abstract a class’ interface from its implementation.
o Using interface, user can specify what a class must do, but not how it does it.
o Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body.
o Once it is defined, any number of classes can implement an interface. Also, one class can
implement any number of interfaces.
o To implement an interface, a class must create the complete set of methods defined by the
interface. However, each class is free to determine the details of its own implementation.
o By providing the interface keyword, Java allows you to fully utilize the “one interface, multiple
methods” aspect of polymorphism.
o Interfaces are designed to support dynamic method resolution at run time.
Defining an Interface:
• An interface is defined much like a class. Following is the general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
• When no access specifier is included, then default access results, and the interface is only
available to other members of the package in which it is declared.
• When it is declared as public, the interface can be used by any other code.
• 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.
• Notice that the methods that are declared have no bodies. They end with a semicolon after
the parameter list. They are, essentially, abstract methods;
• There can be no default implementation of any method specified within an interface.
• Each class that includes an interface must implement all of the methods.
• Variables can be declared inside of interface declarations.
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 18 | 28
Object Oriented Programming with JAVA Module-3
• They are implicitly final and static, meaning they cannot be changed by the implementing
class. They must also be initialized.
• All methods and variables are implicitly public.
• Here is an example that declares a simple interface.
interface Callback {
void callback(int param);
}
Implementing Interfaces:
• Once an interface has been defined, one or more classes can implement that interface.
• To implement an interface, include the implements clause in a class definition, and then
create the methods defined by the interface.
• The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]] {
// class-body
}
• The methods that implement an interface must be declared public.
• Also, the type signature of the implementing method must match exactly the type
signature specified in the interface definition
Here is a small example class that implements the Callback interface shown earlier.
class Client implements Callback {
public void callback(int p) {
[Link]("callback called with " + p);
}
}
• Notice that callback( ) is declared using the public access specifier.
• It is both permissible and common for classes that implement interfaces to define
additional members of their own.
• For example, the following version of Client implements callback( ) and adds the
method nonIfaceMeth( ):
class Client implements Callback {
// Implement Callback's interface
public void callback(int p)
{
[Link]("callback called with " + p);
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 19 | 28
Object Oriented Programming with JAVA Module-3
}
void nonIfaceMeth( ) {
[Link]("Classes that implement interfaces");
}
}
Accessing Implementations Through Interface References:
• You can declare variables as object references that use an interface rather than a class type.
• Any instance of any class that implements the declared interface can be referred to by such
a variable.
• 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. 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.
• The calling code can dispatch through an interface without having to know anything about
the “callee.”
• The following example calls the callback( ) method via an interface reference variable:
class TestIface {
public static void main(String args[ ])
{
Callback c = new Client( );
[Link](42);
}
}
output: callback called with 42
Partial Implementations:
• If a class includes an interface but does not fully implement the methods defined by
that interface, then that class must be declared as [Link] example:
abstract class Incomplete implements Callback
{
int a, b;
void show( ) {
[Link](a + " " + b);
}
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 20 | 28
Object Oriented Programming with JAVA Module-3
// ...
}
• Here, the class Incomplete does not implement callback( ) and must be declared as abstract.
• Any class that inherits Incomplete must implement callback( ) or be declared abstract itself.
Nested Interfaces:
• An interface can be declared a member of a class or another interface. Such an interface
is called a member interface or a nested interface.
• 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.
• 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.
• Thus, outside of the class or interface in which a nested interface is declared, its name must
be fully qualified.
Here is an example that demonstrates a nested interface:
class Animal
{
interface Activity //nested interface
{
void move( );
}
}
class Dog implements [Link]
{
public void move( )
{
[Link]("Dogs can walk and run");
}
}
public class Tester
{
public static void main(String args[ ])
{
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 21 | 28
Object Oriented Programming with JAVA Module-3
Dog d = new Dog( );
[Link]( );
}}
• Notice that Animal defines a member interface called Dog
• Next, Dog implements the nested interface by specifying implements [Link]
• Notice that the name is fully qualified by the enclosing class’ name.
• Inside the main( ) method, an Dog reference called d is created, and it is assigned a reference
to a animal object.
Applying Interfaces:
There are many ways to implement a stack.
• First, here is the interface that defines an integer stack.
This interface will be used by both stack implementations.
// Define an integer stack interface.
interface IntStack {
void push(int item); // store an item
int pop( ); // retrieve an item
}
class FixedStack implements IntStack
{
private int stck[ ];
private int tos;
// allocate and initialize stack
FixedStack(int size) {
stck = new int[size];
tos = -1;
}
// Push an item onto the stack
public void push(int item) {
if(tos==[Link]-1) // use length member
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 22 | 28
Object Oriented Programming with JAVA Module-3
[Link]("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
public int pop( ) {
if(tos < 0) {
[Link]("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
class IFTest {
public static void main(String args[]) {
FixedStack mystack1 = new FixedStack(5);
FixedStack mystack2 = new FixedStack(8);
// push some numbers onto the stack
for(int i=0; i<5; i++)
[Link](i);
for(int i=0; i<8; i++)
[Link](i);
// pop those numbers off the stack
[Link]("Stack in mystack1:");
for(int i=0; i<5; i++)
[Link]([Link]());
[Link]("Stack in mystack2:");
for(int i=0; i<8; i++)
[Link]([Link]());
}}
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 23 | 28
Object Oriented Programming with JAVA Module-3
Variables in Interfaces:
• User can use interfaces to import shared constants into multiple classes by simply declaring
an interface that contains variables that are initialized to the desired values.
• It is as if that class were importing the constant fields into the class name space as final
variables.
• The following example uses this technique to implement an automated “decision maker”:
interface TestInterface
{
final int A = 10;
void display();
}
class Test implements TestInterface {
public void display( )
{
[Link](“displaying interface");
}
}
class Demo{
public static void main(String[ ] args){
Test t = new Test();
[Link]( );
[Link](t.A);
}}
Interfaces Can Be Extended:
• One interface can inherit another by use of the keyword extends.
• When a class implements an interface that inherits another interface, it must provide
implementations for all methods defined within the interface inheritance chain.
Following is an example:
// One interface can extend another.
interface A
{
void meth1( );
void meth2();
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 24 | 28
Object Oriented Programming with JAVA Module-3
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A
{
void meth3( );
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1( )
{
[Link]("Implement meth1( ).");
}
public void meth2( ) {
[Link]("Implement meth2( ).");
}
public void meth3( ) {
[Link]("Implement meth3( ).");
}
}
class IFExtend {
public static void main(String arg[ ]) {
MyClass ob = new MyClass( );
ob.meth1( );
ob.meth2( );
ob.meth3( );
}}
[Link] Interface Methods
A default method lets user to 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.
During its development, the default method was also referred to as an extension method.
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 25 | 28
Object Oriented Programming with JAVA Module-3
A primary motivation for the default method was to provide a means by which interfaces
could be expanded without breaking existing code. There must be implementations for all
methods defined by an interface.
The default method solves this problem by supplying an implementation that will be used if
no other implementation is explicitly provided. Thus, the addition of a default method will not
cause preexisting code to break.
Another motivation for the default method was the desire to specify methods in an interface
that are, essentially, optional, depending on how the interface is used.
As a general rule, default methods constitute a special-purpose feature. The default method
gives user the added flexibility.
2.1 Default Method Fundamentals
An interface default method is defined similar to the way a method is defined by a class.
The primary difference is that the declaration is preceded by the keyword default. For
example, consider this simple interface:
MyIF declares two methods. The first, getNumber( ), is a standard interface method
declaration. It defines no implementation whatsoever. The second method is getString( ),
and it does include a default implementation. In this case, it simply returns the string
"Default String”.
To define a default method, precede its declaration with default.
Because getString( ) includes a default implementation, it is not necessary for an
implementing
class to override it. In other words, if an implementing class does not provide its own
implementation, the default is used. For example, the MyIFImp class shown next is perfectly
valid:
public interface MyIF {
int getNumber( );
default String getString( ) {
return "Default String";
}}
// Implement MyIF.
class MyIFImp implements MyIF {
public int getNumber( ) {
return 100;
}
}
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 26 | 28
Object Oriented Programming with JAVA Module-3
//The following code creates an instance of MyIFImp and uses it to call both getNumber(
) and getString( ). Use the default method.
class DefaultMethodDemo {
public static void main(String[ ] args) {
MyIFImp obj = new MyIFImp( );
[Link]([Link]( ));
[Link]([Link]( ));
}
}
The output is shown here:
100
Default String
2.3 Use static Methods in an Interface
Another capability added to interface by JDK 8 is the ability to define one or more
static methods.
Like static methods in a class, a static method defined by an interface can be called
independently of any object.
Thus, no implementation of the interface is necessary, and no instance of the
interface is required, in order to call a static method. Instead, a static method is
called by specifying the interface name, followed by a period, followed by the
method name. Here is the general form:
[Link]
public interface MyInterface
{
void abstractMethod( );
static void staticMethod( )
{
[Link]("This is a static method in an interface.");
}
}
public class Main {
public static void main(String[ ] args) {
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 27 | 28
Object Oriented Programming with JAVA Module-3
[Link]( );
}
}
2.4 Private Interface Methods
Private interface methods are declared with private access modifier.
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.
interface Test {
default void path( )
{
[Link]("Hello");
baz( );
}
private void baz( ) {
[Link](" world!");
}
}
class demo implements Test{
public static void main(String[ ] args) {
Demo t = new Demo( );
[Link]( );
}
}
Output: Hello world!
Here user cannot call baz( ) because that is private member so call to path( ) is created.
Mrs. Swathi C S, Asst professor, SVIT, Bengaluru P a g e 28 | 28