0% found this document useful (0 votes)
18 views

Module 3

Module 3 covers the concepts of inheritance and interfaces in Java, detailing types of inheritance such as single, multilevel, hierarchical, hybrid, and multiple inheritance. It explains the use of the 'super' keyword for accessing parent class members and constructors, as well as method overriding for runtime polymorphism. Additionally, the module differentiates between method overloading and overriding, emphasizing their respective behaviors and relationships in object-oriented programming.

Uploaded by

akshaykkumbar007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Module 3

Module 3 covers the concepts of inheritance and interfaces in Java, detailing types of inheritance such as single, multilevel, hierarchical, hybrid, and multiple inheritance. It explains the use of the 'super' keyword for accessing parent class members and constructors, as well as method overriding for runtime polymorphism. Additionally, the module differentiates between method overloading and overriding, emphasizing their respective behaviors and relationships in object-oriented programming.

Uploaded by

akshaykkumbar007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

MODULE 3 INHERITANCE and INTERFACES

MODULE 3

 Inheritance:
 Inheritance Basics,
INHERITANCE  Using super,
INTERFACES  Creating a Multilevel Hierarchy,
 When Constructors Are Executed,
 Method Overriding,
 Dynamic Method Dispatch,
 Using Abstract Classes,
 Using final with Inheritance,
 Local Variable Type Inference and Inheritance,
 The Object Class.
 Interfaces:
 Interfaces,
 Default Interface Methods,
 Use static Methods in an Interface,
 Private Interface Methods
MODULE 3 INHERITANCE and INTERFACES

Qp) What is Inheritance? Explain simple and multilevel inheritances in java with
examples?

 One of the most important concepts in object-oriented programming is


inheritance.
 To inherit a class, we simply incorporate the definition of one class into another by using
the extends keyword.
 Definition:
“Creating a new class (child class) from existing class (parent class) is called as
inheritance”.
Or
“Acquiring (taking/Consuming) the properties of one class into another class is
called inheritance.”
Or
“When a new class needs same members as an existing class, then instead of creating
those members again in new class, the new class can be created from existing class,
which is called as inheritance.”

 Main advantage of inheritance is reusability of the code and Method overriding


(polymorphism) can be achieved.
 Using inheritance, we can create a general class that defines traits common to a set
of related items.
 This class can then be inherited by other, more specific classes, each adding those
things that are unique to it. In the terminology of Java, a class that is inherited is
called a superclass.

 The class that does the inheriting is called a subclass. Therefore, a subclass is a
specialized version of a superclass. It inherits all of the instance variables and
methods defined by the superclass and adds its own, unique elements

Base class: is the class from which features are to be inherited into another class.
Syntax:

class Base_Class
{
Members of class
}

Derived class: it is the class in which the base class features are inherited.
Syntax:
class Derived_class extends Base_class
{
Members of class
}
MODULE 3 INHERITANCE and INTERFACES

 Example:
class One //parent class
{
int a=10;
}
class Second extends One
//child class
{

public static void main(String[] args)


{
Second obj=new Second();
System.out.print(obj.a);
}

As shown above child class can access properties (variables or methods) of the parent class

Types of Inheritance:
Inheritance can be classified into 5 types
1. Single Inheritance
2. Multi-Level Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance
5. Multiple Inheritance

1)Single Inheritance:
When a single derived class is created from a single baseclass then the inheritance is called as single
inheritance.

 The below flow diagram shows that class B extends only one class which is A. Here A
is a parent class of B and B would be a child class of A.
MODULE 3 INHERITANCE and INTERFACES

Single Inheritance example program in Java

Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}

Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

2)Multilevel Inheritance:

When a derived class is created from another derived class, then that inheritance is called as multi-level
inheritance.

Base Class Syntax:


class A
{- - - - - }
Derived Class 1
class B extends A
{- - - - -}
Derived Class 2
class C extends B
{---- - -}
MODULE 3 INHERITANCE and INTERFACES

As you can see in below flow diagram C is subclass or child class of B and B is a child class
of A , thereby making this derived class B as the base class for the new class C.

Multilevel Inheritance example program in Java

Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
MODULE 3 INHERITANCE and INTERFACES

3)Hierarchical inheritance:
When more than one derived class is created from a single base class, then that inheritance is called as
hierarchical inheritance.

Base Class
Syntax:
class A
Derived Class 1 Derived Class 2 {- - - - - }

class B extends A
{- - - - -}

class C extends A
{---- - -}

Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends X
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
Y obj1 = new Y();
Obj1.methodY(); // we can access properties of class X and Y
obj.methodZ(); // we can access properties of class X and Z
}
}
MODULE 3 INHERITANCE and INTERFACES

4)Hybrid Inheritance
Any combination of single, hierarchical, multi-level and Multiple inheritances is called as
hybrid inheritance.

Class A

Class B extends A Class D extends A

class C extends B

Example:

public class One


{
void display1()
{
System.out.println("\n class one");
}

}
public class Two extends One
{
void display2()
{
System.out.println("class two");
}

}
public class Three extends Two
{
void display3()
{
System.out.println("class three");
}

}
public class Four extends One
{
void display4()
{
System.out.println("class four");
}
}
MODULE 3 INHERITANCE and INTERFACES

public class Test


{

public static void main(String[] args)


{

Three obj1=new Three();


Four obj2=new Four();
obj1.display1();// we can access properties of class one, two, three

obj1.display2(); //Multilevel Inheritance


obj1.display3();
obj2.display1();// we can access properties of class one and four

obj2.display4();//single Inheritance
}
}

Note: Students should note that the concept explained above is multi level hierarchy (if students got question in
exam Explain how to create multilevel hierarchy, you can use same example)

5)Multiple Inheritance:
In multiple inheritance, one class can have more than one super class (Base class) and inherits
features from all parent classes.
 Note: Java doesn’t supports Multiple Inheritance with class and it can achieved by using
Interfaces.
 Note: Students need explain in the exam by using interface if marks are more.

Syntax:
Base interface 1 Base interface 2 interface A
{- - - - - }

Derived Class interface B


{- - - - -}

class C implements A , B
{- - - - -}
MODULE 3 INHERITANCE and INTERFACES

Qp) Describe the uses of super Keyword.


 The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
 super keyword in java we can use in different ways
 super can be used to refer immediate parent class instance variable.
 super can be used to invoke immediate parent class method.
 super( ) can be used to invoke immediate parent class constructor.

super can be used to refer immediate parent class instance variable.


 We can use super keyword to access the data member or field of parent class.
 It is used if parent class and child class have same fields.

package superexample;

public class One


{
int a=10; //parent class variable name a=10
}

public class Two extends One


{
int a=20; //child class variable name a=20
void display()
{
System.out.println(“child class variable a=” + a);
System.out.println(“parent class variable a=” + super.a);
}
Output:
public static void main(String[] args)
{ Child class variable a=20
Two obj=new Two();
Parent class variable a=10
obj.display();
a. Using super to Call Superclass Constructors
}
A subclass can call a constructor defined by its superclass by use of the following form of
}

super can be used to invoke immediate parent class method.

 The super keyword can also be used to invoke parent class method.
 It should be used if subclass contains the same method as parent class. In other words, itis
used if method is overridden.
MODULE 3 INHERITANCE and INTERFACES

public class One


{
void display()
{
System.out.println(“ hello");
}
}

public class Two extends One


{
void display()
{
super.display();
System.out.println("Computer Science and Design");
}

public static void main(String[] args)


{ Output:
Two obj=new Two();
obj.display(); Hello
} Computer Science and Design
}

super can be used to invoke immediate parent class constructor.


The super keyword can also be used to invoke the parent class constructor.
public class One
{
One()
{
System.out.println("class one is created ");
}
}
public class Two extends One
{
Two()
{
super(); //access parent class constructor
System.out.println("Class two is created");
}
Output:
public static void main(String[] args)
{ class one is created
Two obj=new Two(); Class two is created
}
}
MODULE 3 INHERITANCE and INTERFACES

Qp)When Constructor are executed in Inheritance


A Constructor is a member function of a class that allows you to initialize a newly created object with
some initial value and has same name as class with no explicit return type.
 Whenever a class (sub class) extends another class (super class), a subclass inherits all the
members (fields, methods, and nested classes) from its super class.
 The constructor of the super class can be invoked from the sub class.

Creating Subclass Instance


When we create an object of a subclass, both subclass and superclass members get memory in subclass
object.

Parent Class Default Constructor


In Java, the constructor of super class with no argument (default constructor) gets automatically called in
subclass constructor.

Example
class A {
//default constructor
A() {
System.out.println("A Class Constructor Called ");
}
}

class B extends A {
B() {
System.out.println("B Class Constructor Called ");
}
}

class Main {
public static void main(String[] args) {
//creating B class instance
Super(); //optional for default constructor
B obj = new B(); // super class constructor is automatically called before subclass constructor
}
}
Output
A Class Constructor Called
B Class Constructor Called

 When we create an object of B (Sub class), B class constructor will call and before executing its
code it will invoke default constructor of super class.
MODULE 3 INHERITANCE and INTERFACES

 When the super class has a default constructor, it is not necessary to call it using
the super keyword. It is called automatically.

Calling parent class parameterized constructor


 If we want to call parameterized constructor of superclass in subclass, then we must call it
using super().
Example
class A
{
int a;
A(int x) // parameterized constructor
{
a = x;
}
}

class B extends A
{
int b;
B(int x, int y)
{
super(x); //must be the first statement
b = y;
}

void show()
{
System.out.println("a = " + a + ", b = " + b);
}
}

class Main
{
public static void main(String[] args)
{
B obj = new B(10, 20);
obj.show();

}
}
Output
a = 10, b = 20
 When we create an object of B (sub class), B class parameterized constructor will call and before
executing its code it will execute the parameterized constructor of super class after
reading super(x) statement.
MODULE 3 INHERITANCE and INTERFACES

Method overriding:

 The process of re-implementing the parent class method under the child class with same name
and same number of parameters is called method overriding.
 Method overriding means same method names with same signatures(parameters) in different
classes.
 Method overriding is used to provide the specific implementation of a method which is already
provided by its super class.
 Method overriding is used for runtime polymorphism.
class One
public
{
void display()
{
System.out.println("computer science");
}
}

public class Two extends One


{
void display() //method overriding
{
super.display();
System.out.println("computer science and design");
}
Output:
public static void main(String[] args)
{
computer science
Two obj=new Two();
computer science and design
obj.display();
}
}

Qp) Differentiate between method overloading and method overriding in java ?

Method Overloading Method Overriding


Definition In Method Overloading, Methods of the In Method Overriding, sub class has the same
same class shares the same name but each method with same name and exactly the same
method must have different number of number and type of parameters and same return
parameters or parameters having different type as a super class.
types and order.
Meaning Method Overloading means more than Method Overriding means method of base class
one method shares the same name in the is re-defined in the derived class having same
class but having different signature. signature.
MODULE 3 INHERITANCE and INTERFACES

Behavior Method Overloading is to “add” or Method Overriding is to “Change” existing


“extend” more to method’s behavior. behavior of method.
Overloading and Overriding is a kind of polymorphism. Polymorphism means “one
name, many forms”.
Polymorphis It is a compile time polymorphism. It is a run time polymorphism.
m
Inheritance It may or may not need inheritance in It always requires inheritance in Method
Method Overloading. Overriding.
Signature In Method Overloading, methods must In Method Overriding, methods must have same
have different signature. signature.
Relations In Method Overloading, relationship is In Method Overriding, relationship is there
hip of there between methods of same class. between methods of super class and sub class.
Methods
Criteria In Method Overloading, methods have In Method Overriding, methods have same name
same name different signatures but in the and same signature but in the different class.
same class.
No. of Method Overloading does not require more Method Overriding requires at least two classes
Classes than one class for overloading. for overriding.

Example Class Add Class A


{ {
int sum(int a, int b) void display(int num)
{ {
return a + b; System.out.println(“num=”+num);
} }
int sum(int a) }
{ Class B extends A
return a + 10; {
} void display(int num)
} {
Class overloadDemo{ System.out.println(“num=”+num);
Public static void main(String args[ ]) }
{ }
Add a=new Add( ) ; Class OverridingDemo{
int res1=a.sum(10,20); Public static void main(String args[ ])
System.out.println(“Sum=”+res1); {
int res2=a.sum(10); A a=new A( );
System.out.println(“Sum=”+res2); B b=new B();
a.display(20);
MODULE 3 INHERITANCE and INTERFACES

} b.display(40);
} }
Output: Sum=30 Sum=20 }
Output: num=20 num==40

Qp) What is abstract class? Explain the use of abstract class in inheritance with an
example(create a class figure in java with the following members dim1,dim2 and abstract
method area. Create subclass Triangle, Rectangle, with implementation of area)

 A class which is declared with the abstract keyword is known as an abstract class in Java.
 It can have abstract methods (method without body) and non-abstract methods (method
with the body).
 Abstract class cannot be instantiated(defining an object).
 Abstract method:
 A method without method body is known as abstract method.
 It contains only declaration of the method.
 We can define abstract method using abstract keyword.
 Abstract method must be implemented in child class.
Note: Abstraction is the process of hiding the implementation details and showing only
functionality to the user.

Abstraction is achieved in java using 2 ways

 Using abstract class we can achieve partial abstraction because this class may contains
non-abstract methods also
 Using interface we can achieve 100% abstraction because interface contains only abstract
classes.

 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.
 Abstract class determines the nature of the methods that the subclasses must
implement. One way this situation can occur is when a superclass is unable to create
a meaningful implementation for a method.

 Example:
MODULE 3 INHERITANCE and INTERFACES

package jk;

public abstract class One


{
abstract void display1(); //abstract method

void display2() //Non abstract method


{
System.out.println("This is non abstract method from parent class");
}
}

public class Two extends One


{
void display1()
{
System.out.println("Implementing abstract method in child class");
}

public static void main(String[] args)


{
One obj=new Two(); //Note: we can’t write like One obj=new One( )
obj.display1(); //because abstract class One can’t be instantiated
obj.display2();
}
Output:
}
Implementing abstract method in child class
This is non abstract method from parent class

 Example 2: 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( ).

abstract class Figure


{
double dim1; double dim2;
Figure(double a, double b)
{ dim1 = a;
dim2 = b;
abstract double area();
}

class Rectangle extends Figure {


Rectangle(double a, double b)
MODULE 3 INHERITANCE and INTERFACES

{ super(a, b);
}

double area( ) {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}

class Triangle extends Figure {


Triangle(double a, double b)
{ super(a, b);}

double area( )
{
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}

class AbstractAreas
{
public static void main(String args[])
{
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}

Qp)What are the uses of final, explain with examples?


 The keyword final has three uses.
a. It can be used to create the equivalent of a named constant.
b. to Prevent Overriding
c. to Prevent Inheritance

a)create the equivalent of a named constant:


 final keyword is used to restrict the user to change value of the variable or method or class.
 That is, if the variable is declared as final then we cannot change throughout the program
example: final float PI=3.141f;
MODULE 3 INHERITANCE and INTERFACES

package jk;
final int MAX=10;
public class Two
{
final int a=20 ; //a is final so we can’t change later
void display()
{
a=10; //unable to change value
System.out.println(a);
}

public static void main(String[] args)


{

Two obj=new Two();


obj.display();
} Exception in thread main…….
} Error

b. Using final to Prevent Overriding:-


 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 ( )
{
System.out.println("This is a final method.");
}
}

class B extends A
{
void meth( )
{
//ERROR
System.out.println("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.
MODULE 3 INHERITANCE and INTERFACES

 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.
 Inlining is only an option with final methods. Normally, Java resolves calls to
methods dynamically, at run time. This is called late binding.
 However, since final methods cannot be overridden, a call to one resolved at compile
time. This is called early binding.

c. 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
{
void meth ( )
{
System.out.println("This is a final method.");
}
}

class B extends A
{
void meth( )
{
System.out.println("Illegal!"); //ERROR
}
}

NOTE: it is illegal for B to inherit A since A is declared as final.

Qp) What is dynamic method dispatch? Explain the principle to be followed with example

 Method overriding forms the basis for one of Java’s most powerful concepts: 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.
 Dynamic method dispatch is important because, this is how Java implements run-
time polymorphism.
MODULE 3 INHERITANCE and INTERFACES

 important principle: a superclass reference variable can refer to a subclass object.


Java uses this fact to resolve calls to overridden methods at run time.

 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.
 Thus, this determination is made at run time. When different types of objects are
referred to, different versions of an overridden method will be called.
 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.
 Therefore, if a superclass contains a method that is overridden by a subclass, then
when different types of objects are referred to through super class reference variable,
different versions of the method are executed.
 Example that illustrates dynamic method dispatch:
// Dynamic Method Dispatch
class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}

class B extends A
{
void callme()
{
System.out.println("Inside B's callme method");
}
}

class C extends A
{
void callme()
{
System.out.println("Inside C's callme method");
}
}

class Dispatch
MODULE 3 INHERITANCE and INTERFACES

{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
The output from the program is shown here:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method

Qp) Define Object Class in Java, Explain its methods with example.

 Object class is present in java.lang package.


 Every class in Java is directly or indirectly derived from the Object class.
 If a class does not extend any other class then it is a direct child class of Object and if extends
another class then it is indirectly derived.
 Therefore the Object class methods are available to all Java classes. Hence Object class acts as
a root of the inheritance hierarchy in any Java Program.
MODULE 3 INHERITANCE and INTERFACES

Methods of Object class

Method Description

public final Class getClass() returns the Class, class object of this object. The Class class can
further be used to get the metadata of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() creates and returns the exact copy (clone) of this object.

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's monitor.

public final void wait(long causes the current thread to wait for the specified milliseconds, until
timeout)throws InterruptedException another thread notifies (invokes notify() or notifyAll() method).

protected void finalize() is invoked by the garbage collector before object is being garbage
collected.

What is Local Variable type inference?

 Local variable type inference is a feature in Java 10 that allows the developer to skip the type
declaration associated with local variables (those defined inside method definitions,
initialization blocks, for-loops, and other blocks like if-else).
 It allows to define a variable using var and without specifying the type of it.
 The compiler infers the type of the variable using the value provided.
MODULE 3 INHERITANCE and INTERFACES

 This type inference is restricted to local variables.

String message = "Good bye, Java 9"; var message = "Hello, Java 10";
//Old method declaring //message use var instead of String

 We don’t provide the data type of message. Instead, we mark the message as a var, and the
compiler infers the type of message from the type of the initializer present on the right-hand
side.
Note:1) that this feature is available only for local variables with the initializer.
2) It cannot be used for member variables, method parameters, return types, etc – the initialization
is required, as without which compiler won’t be able to infer the type.

Illegal Use of var

 var won’t work without the initializer:


Ex: var n; // error: cannot use 'var' on variable without initializer
 Won’twork if initialized with null:
Ex:var emptyList = null; // error: variable initializer is 'null'
 It won’t work for non-local variables(global,public):
Ex:public var = "hello"; // error: 'var' is not allowed here

Example for Local Variable type inference

class A {
public static void main(String ags[])
{ Output:
var x = "Hi there"; Hi there
System.out.println(x) ;
1
int[] arr = new int[3];
arr = { 1, 2, 3 }; 2
for (var x = 0; x < 3; x++) 3
System.out.println(arr[x] + "\n");

}
}

Interfaces
An Interface is a collection of abstract methods (methods without definition / only method
declarations) and abstract methods should be implemented by the derived/child class.
MODULE 3 INHERITANCE and INTERFACES

 Keyword here we used is , implements in child class instead of extends keyword


 In the interface, method declaration is not used abstract modifier i.e by default its abstract.
 Interface should not contain any Non-abstract methods (methods with body).
 All interface members by default public.
 By using Interface we can achieve 100% abstraction because interface contains only abstract
methods.
 By using Interface we can achieve Multiple inheritance.

Syntax:

interface interfaceName
{
Method declarations ; //only method protocols- No Implementation
}
Example:

public interface One


{
void display();// abstract method
}

public class Two implements One


{
public void display()
{
System.out.println("abstract method of interface is implemented in child class");
}
public static void main(String[] args)
{
Two obj=new Two();
obj.display();
}
}
MODULE 3 INHERITANCE and INTERFACES

 The interfaces can have abstract methods and variables too, but the variables are final
and static by default(can’t modify it)
public interface One
{
int a=10; //variables are final and static
void display(); // abstract method
}

public class Two implements One


{
public void display()
{
System.out.println("abstract method of interface is implemented in child class");
}
public static void main(String[] args)
{
Two obj=new Two();
obj.display();
System.out.println(“a=” +a); // a=10
Obj.a=20; //Error , you can’t change the value of interface variables
}
}

Multiple Inheritance using Interface


Java does not support multiple inheritance with class. However, we can use interfaces to
implement multiple inheritance.

The following program demonstrates this:

public interface A public interface B


{ {
void display(); Void show();
} }

class X implements A,B


{
public void display()
{
System.out.println("abstract method of interface A is implemented in child class");
}
Void show()
{
System.out.println("abstract method of interface B is implemented in child class");
}

public static void main(String[] args)


{
X obj=new X();
obj.display();
obj.show();
}
}
MODULE 3 INHERITANCE and INTERFACES

Note:

Keywords: extends extends implements can’t implement nor extends

Default Methods in interfaces:


 Before Java 8, interfaces could have only abstract methods.
 The implementation of these methods has to be provided in a separate class.
 if a new method is to be added in an interface, then its implementation code has to be
provided in the class implementing the same interface.
 To overcome this issue, Java 8 has introduced the concept of default methods .
 Default methods allow us to add new method with implementation to an interface
without affecting the classes that implement the interface.
 Default methods are automatically available to all the implementation class of that
interface.
 Default methods are also known as defender methods or virtual extension methods.
 Default methods are used in interface(parent class) not in the child class(implementing
class).

Note: Any object class method names(ex: equals, notify, wait etc) are not used for default
method names.

interface car
{

public void square(int a); // abstract method


default void show()// default method
{
System.out.println("Default Method Executed");
}
}
class TestClass implements TestInterface
{
// implementation of square abstract method
public void square(int a)
{
System.out.println(a*a);
}

public static void main(String args[])


MODULE 3 INHERITANCE and INTERFACES

{
TestClass d = new TestClass();
d.square(4); Output:
// default method executed 16
d.show();
}
Default Method Executed
}

Static Methods in interfaces:


 Java 8 brought a new features to the table, including static and default methods in interfaces.
 Java 8 also allows us to define and implement static methods in interfaces.
 static methods are defined in the interface with the keyword static.
 The static methods in interfaces are similar to default methods but the only difference is that you
can’t override them. Now, why do we need static methods in interfaces if we already have
default methods?
 Suppose you want to provide some implementation in your interface and you don’t want
this implementation to be overridden in the implementing class, then you can declare the
method as static.
 To use a static method, Interface name should be instantiated with it, as it is a part of the
Interface only.

Example: To demonstrate use of Static method in Interface.

Interface one
{
static void hello() // Static Method
{
. System.out.println("static method in interface ");Output:
} static method in interface
} Called from Class

public class InterfaceDemo implements one


{
public static void main(String[] args)
{
// To Call Interface method as Interface name is preceding with method
one.hello();
}

static void hello() // Class Static method is defined// used in static main also
{
System.out.println("Called from Class");
}
}
MODULE 3 INHERITANCE and INTERFACES

Private Methods in Interfaces


 Java 9 onwards, you can include private methods in interfaces. Before Java 9 it was not possible.
 These methods are visible only inside the class/interface, so it's recommended to use private
methods for confidential code.
 private methods that help to share common code between non-abstract methods.
 These private methods will improve code re-usability inside interfaces and will provide choice
to expose only our intended methods implementations to users.
 These methods are only accessible within that interface only and cannot be accessed or
inherited from an interface to another interface or class.

Syntax
private void methodName() {
// some statementscode
}
Example
interface Operation
{
default void addition()
{
System.out.println("default method addition");
}
default void multiply()
{
division(); // private method is called in default method
System.out.println("default method multiply");
}
private void division() // private method
{
System.out.println("private method division");
}
} Output:
private method division
class Test implements Operation
{ default method multiply
public static void main(String args[])
{
Test test = new Test();
test.multiply();
test.division(); // error, we can’t call the private method

}
}
MODULE 3 INHERITANCE and INTERFACES

Private methods can be implemented as both static and non-static.


interface Operation
{
default void addition()
{
System.out.println("default method addition");
division(); // private method is called in default method
}
private static void multiply()
{
division(); // Error, private non-static method can’t use in private static method
System.out.println("default method multiply");
}
private void division() // private method
{
System.out.println("private non- static method in division");
Multiply(); // private static method
}
} Output:
default method multiply
class Test implements Operation private non- static method in division
{ default method multiply
public static void main(String args[])
{
Test test = new Test();
test.multiply();
test.division(); // error, we can’t call the private method

}
}

Rules For using Private Methods in Interfaces


 Private interface method cannot be abstract.
 Private method can be used only inside interface and other static and non-static interface
methods.
 Private non-static methods cannot be used inside private static methods.
 Private method can be used within default method of the interface .
MODULE 3 INHERITANCE and INTERFACES

You might also like