Inheritance 3
Inheritance 3
Inheritance
• Inheritance is an important pillar of OOP(Object-Oriented
Programming).
• It is the mechanism in java by which one class is allowed to inherit the
features(fields and methods) of another class.
Important terminology:
• Super Class: The class whose features are inherited is known as
superclass(or a base class or a parent class).
• Sub 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.
• Reusability: Inheritance supports the concept of “reusability”, i.e.
when we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
The keyword used for inheritance is extends.
Syntax :
Class base-class
{
…..
}
BabyDog class inherits the Dog class which again inherits the Animal class,
so there is a multilevel inheritance
class Animal{ class TestInheritance2{
void eat()
{System.out.println("eating...");} public static void main(St
} ring args[]){
class Dog extends Animal{ BabyDog d=new BabyDog(
void bark() );
{System.out.println("barking...");}
}
d.weep();
class BabyDog extends Dog{ d.bark();
void weep() d.eat();
{System.out.println("weeping...");}
} }}
Hierarchical Inheritance
class A { public class Test {
public void print_A() { System.out.println("Class public static void main(String[]
A"); } args)
} {
B obj_B = new B();
class B extends A { obj_B.print_A();
public void print_B() { System.out.println("Class obj_B.print_B();
B"); }
} C obj_C = new C();
obj_C.print_A();
class C extends A { obj_C.print_C();
public void print_C() { System.out.println("Class
C"); } D obj_D = new D();
} obj_D.print_A();
obj_D.print_D();
class D extends A { }
public void print_D() { System.out.println("Class }
D"); }
}
Super Keyword in Java
• The super keyword in java is a reference variable that
is used to refer parent class objects.
• The keyword “super” came into the picture with the
concept of Inheritance. It is majorly used in the
following contexts:
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " +
super.maxSpeed);
}
}
2. Use of super with methods: This is used when we want to call parent class
method.
So whenever a parent and child class have same named methods then to
classresolve
Person ambiguity we use super keyword.
{
void message()
{
System.out.println("This is person class");
} class Test
}
{
/* Subclass Student */ public static void main(String args[])
class Student extends Person {
{ Student s = new Student();
void message()
{ // calling display() of Student
System.out.println("This is student class");
s.display();
}
}
// Note that display() is only in Student class }
void display()
{
// will invoke or call current class message()
method
message();
class Person
{
Person()
{
System.out.println("Person class
Constructor"); class Test
} {
}
public static void main(String[]
/* subclass Student extending the Person class */
args)
class Student extends Person {
{ Student s = new Student();
Student() }
{ }
// invoke or call parent class constructor
super();
System.out.println("Student class
Constructor");
}
}
• Write a Java program to demonstrate multilevel inheritance with an employee hierarchy. Create a base class
Employee with attributes name and employeeId, and a method displayInfo(). Derive a class Manager from
Employee, adding an attribute department and overriding displayInfo() to include department information.
Further, derive a class SeniorManager from Manager, adding an attribute region and overriding
displayInfo() to include region information. Implement constructors and methods to initialize and display
details for each class
class Employee { // Derived class from Employee
super.displayInfo();
System.out.println("Employee ID: " +
employeeId); System.out.println("Department: " + department);
} }
}
}
// Further derived class from Manager }
class SeniorManager extends Manager { // Main class to test the hierarchy
private String region; public class EmployeeHierarchy {
// Constructor for SeniorManager public static void main(String[] args) {
public SeniorManager(String name, String // Create an instance of SeniorManager
employeeId, String department, String region) {
SeniorManager seniorManager = new
super(name, employeeId, department); SeniorManager("Alice Johnson", "E123", "Sales",
this.region = region; "North America");
}
// Overriding displayInfo() method
// Display information
public void displayInfo() { seniorManager.displayInfo();
super.displayInfo();
}
System.out.println("Region: " + region);
} }
Exercise-
} }
} }
// Main class to test the implementation
Write a Java program to implement hierarchical inheritance. Create a base class Shape with a
method area(). Derive two classes, Circle and Rectangle, from Shape. Override the area()
method in both subclasses to calculate and display the area of a circle and a rectangle,
respectively. Use appropriate constructors to initialize the attributes (radius for the circle, length,
and width for the rectangle).
// Base class
// Derived class Rectangle
class Shape { class Rectangle extends Shape {
void area() { private double length;
System.out.println("Area of the shape"); private double width;
}
}
// Constructor to initialize length and width
// Derived class Circle
class Circle extends Shape {
public Rectangle(double length, double width) {
private double radius; this.length = length;
this.width = width;
// Constructor to initialize radius }
public Circle(double radius) {
this.radius = radius;
@Override
}
void area() {
@Override
void area() { double area = length * width;
double area = Math.PI * radius * radius; System.out.printf("Area of Rectangle: ", area);
System.out.printf("Area of Circle: ", area); }
} }
}
// Main class to test the implementation
public class Main {
public static void main(String[] args) {
// Create instances of Circle and Rectangle
Shape circle = new Circle(5.0); // Radius = 5.0
Shape rectangle = new Rectangle(4.0, 6.0); // Length = 4.0, Width =
6.0
• There are situations in which you will want to define a superclass that declares the structure
of a given abstraction without providing a complete implementation of every method.
• That is, 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.
• Such a 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.
• You can require that certain methods be overridden by subclasses by specifying the
abstract type modifier. These methods are sometimes referred to as subclasser
responsibility because they have no implementation specified in the superclass.
• Thus, a subclass must override them—it cannot simply use the version defined in the
superclass. To declare an abstract method, use this general form:
abstract type name(parameter-list);
• Any class that contains one or more abstract methods must also be declared abstract.
• To declare a class abstract, you simply use the abstract keyword in front of the class
keyword at the beginning of the class declaration.
• There can be no objects of an abstract class. That is, an abstract class cannot be
directly instantiated with the new operator.
• Such objects would be useless, because an abstract class is not fully defined. Also, you
cannot declare abstract constructors, or abstract static methods.
• Any subclass of an abstract class must either implement all of the abstract methods in
the superclass, or be declared abstract itself.
• Here is a simple example of a class with an abstract method, followed by a class which
implements that method:
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
// Using abstract methods and classes. class Triangle extends Figure {
class Rectangle extends Figure { // Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Rectangle(double a, double b) {
Triangle t = new Triangle(10, 8);
super(a, b);
Figure figref; // this is OK, no object is created
}
figref = r;
// override area for rectangle System.out.println("Area is " + figref.area());
double area() { figref = t;
System.out.println("Inside Area for Rectangle."); System.out.println("Area is " + figref.area());
return dim1 * dim2; }
} }
}
Using final with Inheritance