Module 3
Module 3
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?
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
{
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
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.
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.
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 C extends B
Example:
}
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
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
{- - - - - }
class C implements A , B
{- - - - -}
MODULE 3 INHERITANCE and INTERFACES
package superexample;
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
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.
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");
}
}
} 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.
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;
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( ).
{ super(a, b);
}
double area( ) {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
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());
}
}
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);
}
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.
class B extends A
{
void meth( )
{
System.out.println("Illegal!"); //ERROR
}
}
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
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.
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 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.
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
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.
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
Syntax:
interface interfaceName
{
Method declarations ; //only method protocols- No Implementation
}
Example:
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
}
Note:
Note: Any object class method names(ex: equals, notify, wait etc) are not used for default
method names.
interface car
{
{
TestClass d = new TestClass();
d.square(4); Output:
// default method executed 16
d.show();
}
Default Method Executed
}
Interface one
{
static void hello() // Static Method
{
. System.out.println("static method in interface ");Output:
} static method in interface
} Called from Class
static void hello() // Class Static method is defined// used in static main also
{
System.out.println("Called from Class");
}
}
MODULE 3 INHERITANCE and INTERFACES
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
}
}