Unit III
Inheritance, Interface and
Package
Mr. R. M. Patil
SY CO, JPR
2023-2024
3.1. Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires
all the properties and behaviors of a parent object. It is an
important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create
new classes that are built upon existing classes. When you inherit
from an existing class, you can reuse methods and fields of the
parent class.
Moreover, you can add new methods and fields in your current
class also.
Inheritance represents the IS-A relationship which is also
known as a parent-child relationship.
3.1. Inheritance in Java
Why use inheritance in java:
For Method Overriding (so runtime polymorphism can be
achieved).
For Code Reusability.
3.1. Inheritance in Java
Terms used in Inheritance:
Class: A class is a group of objects which have common
properties. It is a template or blueprint from which objects are
created.
Sub Class/Child Class: Subclass is a class which inherits the
other class. It is also called a derived class, extended class, or
child class.
Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a
parent class.
Reusability: As the name specifies, reusability is a mechanism
which facilitates you to reuse the fields and methods of the
existing class when you create a new class. You can use the same
fields and methods already defined in the previous class.
3.1. Inheritance in Java
The syntax of Java Inheritance:
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new
class that derives from an existing class. The meaning of
"extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is
called a parent or superclass, and the new class is called child
or subclass.
3.1. Inheritance in Java
Java Inheritance Example:
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus); }
}
3.1. Inheritance in Java – Types of Inheritance
3.1. Inheritance in Java – Types of Inheritance
Note: Multiple inheritance is not
supported in Java through class.
3.2. Inheritance in Java – 1. Single Inheritance
When a class inherits another class, it is known as a single
inheritance.
3.2. Inheritance in Java – 1. Single Inheritance
In the example given below, Derived class inherits the Base class, so there is the
single inheritance.
class Base class test
{ {
public void M1() public static void main(String args[])
{ {
System.out.println(“ Base Class Method ”); Derived d = new Derived();
} d.M1(); //Print base class method
} d.M2(); //Print derived class method
class Derived extends Base }
{ }
public void M2()
{
System.out.printIn(“ Derived Class Methods “);
}
}
3.2. Inheritance in Java – 2. Multilevel Inheritance
When there is a chain of inheritance, it is known
as multilevel inheritance.
3.2. Inheritance in Java – 2. Multilevel Inheritance
As you can see in the example given below, derived2 class inherits the derived1 class which
again inherits the Base class, so there is a multilevel inheritance.
class derived2 extends derived1
class Base {
{ void M3()
void M1() {
{ System.out.println(“Derived2...");
System.out.println(“Base..."); }
} }
} class Test
class derived1 extends Base {
public static void main(String args[])
{
{
void M2() derived2 d=new derived2();
{ d.M1();
System.out.println(“Derived1."); d.M2();
} d.M3();
} }
}
3.2. Inheritance in Java – 3. Hierarchical Inheritance
When two or more classes inherits a single class, it is
known as hierarchical inheritance.
3.2. Inheritance in Java – 3. Hierarchical Inheritance
In the example given below, B and C classes inherits the A class, so there is hierarchical
inheritance.
class C extends A
class A {
{ void M3()
void M1() {
{ System.out.println(“Class C...");
System.out.println(“Class A..."); }
}
}
class Test
} {
class B extends A public static void main(String args[])
{ {
void M2() C c1=new C();
{ c.M1();
System.out.println(“Class B..."); c.M3();
} //c.M2(); //C.T.Error
} }
}
Homework
1. Explain inheritance feature of Java – W17, 2M
2. What is single level inheritance? Explain with Suitable Example. S17, 6M
3. Create a class student having mothod getdata() which should accept details
of student such as rollno, name and marks of 3 subjects. Extend class result
from student. Define a method cal() in result to calculate the total and
average of marks and display it. 4M
4. Write a program to implement following inheritance. W14, 4M
Class: person
name, age
Class: employee
emp_designation
emp_Salary
Homework
5. Write a Java Program to Implement multilevel inheritance with
4 levels of hierarchy. S18, 8M
6. Explain hierarchical inheritance with example. 4M
3.2. Why multiple inheritance is not supported in java?
To reduce the
complexity and simplify class A class B
the language, multiple { {
inheritance is not void msg() void msg()
{ {
supported in java.
System.out.println("Hello"); System.out.println("Welcome");
Consider a scenario } }
}
where A, B, and C are }
three classes. The C class C extends A,B
class inherits A and B {
classes. public static void main(String args[])
{
If A and B classes
C obj=new C();
have the same method obj.msg();
and you call it from child //Now which msg() method would be invoked?
class object, there will }
be ambiguity to call the }
method of A or B class.
3.2. Constructor Overriding
We can define constructors in base and derived class.
As we know constructor get automatically invoked when
an object for the class is created.
In inheritance usually we create object for only derived
class.
If the base class has default constructor, then it get
automatically called on object creation for derived class.
3.2. Constructor Overriding
class base class demo
{ {
base() public static void main(String[] args)
{ {
System.out.println(“BASE”); derived d = new derived();
} }
} }
class derived extends base
Derived class
{ object
derived() creation
{ invokes both
System.out.println(“Derived”); base and
} derived
constructors
}
3.2. Parameterized Constructor in Base Class
We have already seen that, the parent class is known as
Superclass while child class is known as subclass.
Now continuing with previous section, if the base class
has parameterized constructor then it does not get invoked
automatically by the creation of derived class object.
We have to call it using super keyword in derived class
constructor.
3.2. Parameterized Constructor in Base Class
Class derived extends base
class base {
{ int b;
int a; derived (int x, int y)
base (int z) {
{ super(x); Calls base constructor
a=z; b = y;
System.out.println(a); System.out.println(b);
} }
} }
class test
{
public static void main(String args[])
{
Calls only derived
derived d = new derived(10,20);
constructor
}
}
3.2. Method Overriding in Java
If subclass (child class) has the same method as declared
in the parent class, it is known as method overriding in Java.
In other words, If a subclass provides the specific
implementation of the method that has been declared by
one of its parent class, it is known as method overriding.
Usage of Java Method Overriding:
Method overriding is used to provide the specific
implementation of a method which is already provided by its
superclass.
Method overriding is used for runtime polymorphism
3.2. Method Overriding in Java
Rules for Java Method Overriding:
1. The method must have the same name as in the parent
class
2. The method must have the same parameter as in the
parent class.
3. There must be an IS-A relationship (inheritance).
In Method Overriding, methods with same signature (name and
arguments) are defined in base and derived classes.
In this case the derived class object can call only derived class
method. To call base class overridden method, we have to use
again super keyword.
3.2. Method Overriding in Java
Class derived extends base
class base {
{ void display()
void display () {
{ super.display(); Calls to base method
System.out.println(“Base Class”); System.out.println(“Derived Class”);
} }
} }
class test
{
public static void main(String args[])
{
derived d = new derived();
d.display(); Calls derived method
}
}
3.2. Method Overriding Vs. Overloading in Java
S.NO Method Overloading Method Overriding
Method overloading is a compile time Method overriding is a run time
1.
polymorphism. polymorphism.
While it is used to grant the specific
It help to rise the readability of the implementation of the method which is
2.
program. already provided by its parent class or
super class.
While it is performed in two classes with
3. It is occur within the class.
inheritance relationship.
Method overloading may or may not While method overriding always needs
4.
require inheritance. inheritance.
In this, methods must have same While in this, methods must have same
5.
name and different signature. name and same signature.
In method overloading, return type
While in this, return type must be same or
6. can or can not be be same, but we
co-variant.
must have to change the parameter.
3.2. Use of “super” keyword
The super keyword in java is a reference variable that is
used to refer parent class objects.
3.2. Use of “super” keyword
class base class test
{ {
int a; public static void main(String args[])
} {
Class derived extends base derived d = new derived();
{
int a; d.display();
void display() }
{ }
a=10;
super.a=20; Calls to base class member
System.out.println(“a”);
System.out.println(“super.a”);
}
}
3.2. Runtime Polymorphism or Dynamic method dispatch
Runtime Polymorphism in Java is achieved by Method
overriding in which a child class overrides a method in its
parent.
An overridden method is essentially hidden in the parent
class, and is not invoked unless the child class uses the super
keyword within the overriding method.
This method call resolution happens at runtime and is
termed as Dynamic method dispatch mechanism.
3.2. Runtime Polymorphism or Dynamic method dispatch
When Parent class
reference variable refers
to Child class object, it is
known as Upcasting.
In Java this can be
done and is helpful in
scenarios where multiple
child classes extends one
parent class.
3.2. Runtime Polymorphism or Dynamic method dispatch
A a1 = new A();
a1.show(); Calls to show() of class A A
show()
a1 = new B();
a1.show(); Calls to show() of class B B C D
show() show() show()
a1 = new C();
a1.show(); Calls to show() of class C
a1 = new D();
a1.show(); Calls to show() of class D
3.2. Runtime Polymorphism or Dynamic method dispatch
class Bike
{
void run()
{
System.out.println("running");
} Output:
}
class Splendor extends Bike running safely with
{ 60km.
void run()
{
System.out.println("running safely with 60km");
}
public static void main(String args[])
{
Bike b = new Splendor(); //upcasting
b.run();
}
}
3.2. Java “final” keyword
In Java, the final keyword is used to denote constants.
It can be used with variables, methods, and classes.
Once any entity (variable, method or class) is
declared final, it can be assigned only once.
That is,
- the final variable cannot be reinitialized with another value
- the final method cannot be overridden
- the final class cannot be extended
3.2. Java “final” keyword
1. Java final Variable
In Java, we cannot change the value of a final variable.
For example:
class test
{
Error
public static void main(String[] args) cannot assign a value to
{ final variable AGE AGE
= 45; ^
final int AGE = 32;
AGE = 45; //Error
System.out.println("Age: " + AGE);
}
}
3.2. Java “final” keyword
2. Java final Method: In Java, the final method cannot be overridden by the
child class. For example,
class FinalDemo
{
public final void display()
{
System.out.println("This is a final method.");
}
} Error
display() in Main cannot
class test extends FinalDemo override display() in
{ FinalDemo public final void
void display() display() { ^ overridden
{ method is final
System.out.println("The final method is overridden.");
}
public static void main(String[] args)
{
test obj = new test();
obj.display();
}
}
3.2. Java “final” keyword
3. Java final Class: In Java, the final class cannot be inherited by another
class. For example,
final class FinalClass
{
public void display()
{
System.out.println("This is a final method."); Error
} cannot inherit from
}
class test extends FinalClass
final FinalClass class
{ Main extends
public void display() FinalClass {
{
System.out.println("The final method is overridden.");
}
public static void main(String[] args)
{
test obj = new test();
obj.display();
}
}
3.2. Java “final” keyword
3. Java final Class:
There are various predefined final classes in java.
1. String
2. Math
3. Hashtable
4. Socket
5. StringBuffer
6. Vector
7. Thread
Homework
1. Explain with example (a) Constructor Overriding (b)
Parameterized Constructor in Base Class. 6M
2. Explain Method Overriding with Example. W17, 4M
3. State the use of ‘super’ w.r.t. inheritance with example. W15,
S16, W17– 4M
4. Explain the concept of dynamic method dispatch in java with
suitable example. W17, 4M
5. Write a program to implement inheritance and polymorphism in
Java. W17, 4M
6. State three uses of ‘final’ keyword with example. W14, S16, S17,
4M
3.2. Abstract Methods and Classes
A class which is declared with the abstract keyword is known as an
abstract class in Java.
Data abstraction is the process of hiding certain details and
showing only essential information to the user.
The abstract keyword is a non-access modifier, used for classes and
methods:
Abstract class: is a restricted class that cannot be used to create
objects (to access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does
not have a body. The body is provided by the subclass (inherited
from).
3.2. Abstract Methods and Classes
Abstract class:
A class is declared abstract using the abstract keyword.
It can have zero or more abstract and non-abstract methods.
We need to extend the abstract class and implement its methods.
It cannot be instantiated.
Syntax for abstract class:
abstract class class_name
{
//abstract or non-abstract methods
}
3.2. Abstract Methods and Classes
Abstract class:
abstract class Animal
{
public abstract void
animalSound();
public void sleep()
{
System.out.println("Zzz");
}
}
From the example above, it is not possible to create an object of
the Animal class:
Animal obj = new Animal(); // will generate an
error
3.2. Abstract Methods and Classes
Abstract Method:
A method declared using the abstract keyword within an abstract class
and does not have a definition (implementation) is called an abstract
method.
When we need just the method declaration in a super class, it can be
achieved by declaring the methods as abstracts.
Abstract method is also called subclass responsibility as it doesn't have the
implementation in the super class. Therefore a subclass must override it to
provide the method definition.
Syntax for abstract method:
abstract return_type method_name( [ argument-list ] );
3.2. Abstract Methods and Classes
3.2. Abstract Methods and Classes
abstract class Bike
{
abstract void run();
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Honda obj = new Honda();
obj.run();
}
}
abstract class Shape class Test
{ {
abstract void draw(); public static void main(String args[])
{
} Shape s = new Circle();
class Rectangle extends Shape s.draw();
{ }
void draw() }
{
System.out.println("drawing rectangle");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("drawing circle");
}
}
3.2. Java “static” keyword
Static keyword can be used with class, variable, method
and block.
Static members belong to the class instead of a specific
instance, this means if you make a member static, you can
access it without object.
The static can be:
Variable (also known as a class variable) [Ex:static int a;]
Method (also known as a class method)
Block
Nested class
3.2. Java “static” keyword
class SimpleStaticExample
{
static void myMethod()
{
System.out.println("myMethod"); Static Method
}
public static void main(String[] args)
{
/* You can see that we are calling this
* method without creating any object.
*/
myMethod();
}
}
3.2. Java “static” keyword
class JavaExample
Static
{
static int num = 97; Variables
static String mystr = “Static keyword in Java”;
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}
}
3.2. Java “static” keyword
class JavaExample
{
static int num;
static String mystr; Static Variables &
static
Block
{
num = 97;
mystr = "Static keyword in Java";
}
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}
}
Homework
1. Explain abstract class with suitable example. W14, 4M
2. Explain static keyword in java with example. 4M