Inheritance
Prepared by
Jesna J S
Assistant Professor CSE, TKMCE
Topics Include
• Inheritance - Basics and Types
• super keyword
• calling superclass constructor from child class constructor
• Method Overriding
• using final with inheritance
Why Use Inheritance in Java?
Inheritance 1. Code Reusability: The code written in
the Superclass is common to all
• It is the mechanism in Java by subclasses. Child classes can directly
which one class is allowed to use the parent class code.
inherit the features(fields and 2. Method Overriding: Method
methods) of another class. Overriding is achievable only through
• In Java, Inheritance means creating Inheritance. It is one of the ways by
new classes based on existing which Java achieves Run Time
ones. Polymorphism.
• A class that inherits from another 3. Abstraction: The concept of
class can reuse the methods and abstraction where we do not have to
fields of that class. provide all details, is achieved through
inheritance. Abstraction only shows the
functionality to the user.
• The class whose features are inherited is known as a superclass(or a base class
or a parent class).
• The class that inherits the other class is known as a subclass(or a derived class,
extended class or child class).
• The subclass can add its own fields and methods in addition to the superclass
fields and methods.
• Extends keyword is used to inherit properties from a superclass.
class ChildClass extends ParentClass
{
// Additional fields and methods
}
class A { class B extends A {
int a,b; int k;
A() { B() {
a=5; k=15; }
b=10; } void show1() {
void show() { [Link]("I am the Child
[Link]("I am the Class"); }
SuperClass"); } void print1() {
void print() { [Link](k+a+b); } }
[Link](a+"\t"+b); }
}
public class Main2 {
public static void main(String[] arg) {
A objA=new A();
B objB=new B();
[Link]("Superclass is printing..");
[Link]();
[Link]("Subclass calls superclass..");
[Link]();
[Link]("Subclass is printing..");
objB.show1();
[Link]("Superclass's variables is printing..");
[Link]();
[Link]("Subclass calls superclass ..");
[Link]();
[Link]("Subclass's variables is printing..");
objB.print1(); } }
Member Access and Inheritance
• A class member that has been declared as private will remain private to its
class.
• It is not accessible by any code outside its class, including subclasses.
✓private → only in same class.
✓default → same package only.
✓protected → same package + subclasses outside package.
✓public → everywhere.
A Superclass Variable Can Reference a Subclass Object
• A reference variable of a superclass can be assigned a reference to any subclass
derived from that superclass.
class Animal{ public class Main3{
void sound(){ public static void main(String[] arg){
[Link]("Animal Animal a=new Animal();
make a sound"); [Link]();
}} Dog d=new Dog();
[Link]();
//superclass object referencing sub
class Dog extends Animal{ class object
void sound(){ a=d;
[Link]("Dog Barks"); [Link]();
}} }}
LAB Work
Write a Java program to demonstrate inheritance.
▪ Create a class Box that stores the dimensions of a box (width, height, depth) and
includes:
✓Constructors for initializing objects in different ways.[If all dimensions are
given/some are given/no dimensions are given when creating the object]
✓A method volume() to calculate the volume of the box.
▪ Then, create a subclass BoxWeight that extends Box by adding an instance variable
weight.
✓Constructor for initializing objects.
▪ Write a main class DemoBoxWeight to:
✓Create two BoxWeight objects with different dimensions and weights.
✓Display their volumes and weights.
✓Assign the reference of BoxWeight to a Box reference variable.
✓Show that the Box reference can access the volume() method but cannot access
the weight variable.
Using super keyword
Two uses:
1. Access superclass constructors:
• When a subclass is created, the superclass constructor must run first to
initialize the inherited fields.
• We use super(...) to explicitly call the superclass constructor.
2. Access superclass methods:
• If a subclass overrides a method from its superclass, we can still call the
superclass version using [Link]()
1. Access superclass constructors:
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}}
class BoxWeight extends Box {
double weight;
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call Box constructor
weight = m;
}}
class Animal {
2. Access superclass methods:
void sound() {
[Link]("Animal makes a sound"); }}
class Dog extends Animal {
void sound() {
[Link](); // call Animal’s sound()
[Link]("Dog barks"); } }
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); } }
Method Overriding
• Method overriding happens when a subclass provides its own
implementation of a method that is already defined in the superclass.
• The method in the subclass must have the same name, return type, and
parameters as in the super class.
• It allows runtime polymorphism (dynamic method dispatch).
• Should follow same method signature ie, method name and parameters must
match.
• Return type must be the same.
• Access modifier → can’t reduce visibility (e.g., if parent method is public,
child can’t make it private).
• Only inherited methods can be overridden (not private, not final, not
static).
class A class B extends A public class Override
{ { {
int i,j; int k; public static void main(String[]
A(int a,int b) { B(int a,int b,int c) { arg) {
i=a; super(a,b); B OBJ1=new B(5,10,15);
j=b; k=c; [Link]();//this calls show()
} in B
}
void show() { }
void show() {
}
[Link]("i
[Link](" = "+i+"\nj = "+j+"\nk
i = "+i+"j = "+j); = "+k);
} }
} }
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.
• A reference variable of a superclass can refer to an object of any subclass
A ref;
ref = new B(); // superclass reference -> subclass object
• When a method is overridden in a subclass, Java decides at runtime which version of
the method to execute.
• The decision depends on the type of the object being referred to, not the reference
type.
• Compiler checks whether the method exists in the reference type (superclass).
• At runtime, the JVM binds the method call to the actual object’s version.
Practice Question
Write a Java program to demonstrate method overriding and dynamic method
dispatch using the following requirements:
▪ Create a superclass Figure with two data members dim1 and dim2, a
constructor to initialize them, and a method area() that prints "Area for Figure
is undefined" and returns 0.
▪ Create two subclasses:
✓Rectangle that overrides area() to compute the area of a rectangle.
✓Triangle that overrides area() to compute the area of a triangle.
▪ In the main method, declare a reference variable of type Figure. Assign it
objects of Rectangle, Triangle, and Figure in turn, and display their areas.
Using final with Inheritance
• The final keyword in Java has special meaning when used with inheritance.
• The keyword final has the uses.
1. Using final to Prevent Overriding
2. Using final to Prevent Inheritance
Using final to Prevent Overriding
• If a method is declared as final, it cannot be overridden by subclasses.
• However, it can still be inherited.
class A {
final void show() {
[Link]("This is a final method in class A");
}
}
class B extends A {
// Error: Cannot override the final method from A
// void show() { ... }
}
Using final to Prevent Inheritance
• If a class is declared as final, it cannot be inherited.
• This prevents other classes from extending it.
final class Vehicle {
void display() {
[Link]("This is a vehicle");
}
}
// Error: Cannot inherit from final Vehicle
//class Car extends Vehicle {
//}
Abstract Classes
• An abstract class in Java is a class that is declared with the keyword
abstract.
• It cannot be instantiated (you cannot create an object of it).
• It can have both abstract methods (without body) and concrete methods
(with body).
Abstract Method
✓Declared using the abstract keyword.
✓Has no body, only a method signature.
✓Must be implemented in the subclass (unless the subclass is also
abstract).
abstract data_type name(parameter-list);
Note::
▪ If a class extends an abstract class, then it must provide
implementation for all abstract methods of the superclass.
▪ If it doesn’t, then that subclass itself must also be declared
abstract.
public class Mainclass2
abstract class A{ {
void display(){ public static void main(String[] arg)
[Link]("Super class is displaying"); {
} B obj=new B();
abstract void AbstDisplay();
[Link]();
}
[Link]();
class B extends A{ [Link]();
void displayNew(){ }}
[Link]("Sub class is displaying");
}
void AbstDisplay(){
[Link]("Abstract method is displaying");
}}
Self Learning….
1. What are the different types of inheritance supported in JAVA??
2. Explain each with an example.