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

Inheritance 3

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

Inheritance 3

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

Inheritance

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
{
…..
}

class derived-class extends base-class


{
//methods and fields
}
Types of Inheritance
1.Single Inheritance(only one super class)
2.Hierarchical Inheritance(one super class, many sub classes)
3.Multilevel Inheritance(Derived from a derived class)
4.Multiple Inheritance(several super classes)
5.Hybrid Inheritance
Example of Single Inheritance
System.out.println("The product of the given numbers:"+z);
}
class Calculation
{
public static void main(String args[])
int z; {
public void addition(int x, int y) int a = 20, b = 10;
{ My_Calculation demo = newMy_Calculation();
z = x + y;
System.out.println("The sum of the given
numbers:"+z); demo.addition(a, b);
}
public void Subtraction(int x, int y)
{
demo.Subtraction(a, b);
z = x - y;
System.out.println("The difference demo.multiplication(a, b);
between the given numbers:"+z);
}
}
} }
Output:
public class My_Calculation extends The sum of given number is: 30
Calculation { The difference between given number is : 10
The product of given number is: 200
public void multiplication(int x, int y)
{
z = x * y;
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance.

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:

1. Use of super with variables


• This scenario occurs when a derived class and base
class has same data members.
• In that case there is a possibility of ambiguity for the
JVM.
Example
class Vehicle class Test
{ {
int maxSpeed = 120; public static void main(String[]
} args)
{
/* sub class Car extending vehicle */ Car small = new Car();
class Car extends Vehicle small.display();
{ }
int maxSpeed = 180; }

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();

// will invoke or call parent class message()


method
super.message();
}
}
3. Use of super with constructors: super keyword can also be used to access the parent class
constructor.
One more important thing is that, ‘’super’ can call both parametric as well as non parametric
constructors depending upon the situation

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

protected String name; class Manager extends Employee {

protected String employeeId; protected String department;

// Constructor for Employee // Constructor for Manager

public Manager(String name, String employeeId, String


public Employee(String name, String employeeId) {
department) {
this.name = name;
super(name, employeeId);
this.employeeId = employeeId; this.department = department;
} }

// Method to display employee information // Overriding displayInfo() method

public void displayInfo() { @Override

System.out.println("Name: " + name); public void displayInfo() {

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-

Write a Java program to demonstrate method overriding using inheritance. Create a


base class Animal with a method sound(). Create a derived class Dog that overrides
the sound() method to print "Bark". Similarly, create a Cat class that overrides the
sound() method to print "Meow". Call the sound() method from both subclasses.
// Base class class Cat extends Animal {

class Animal { @Override

void sound() { void sound() {

System.out.println("Animal makes a sound"); System.out.println("Meow");

} }

} }
// Main class to test the implementation

// Derived class Dog public class Main {

class Dog extends Animal { public static void main(String[] args) {

@Override // Create instances of Dog and Cat

void sound() { Animal myDog = new Dog();

System.out.println("Bark"); Animal myCat = new Cat();

} // Call the sound method on each instance

} myDog.sound(); // Outputs: Bark


myCat.sound(); // Outputs: Meow
}
}
Exercise

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

// Call the area method on each instance


circle.area(); // Outputs: Area of Circle: 78.54
rectangle.area(); // Outputs: Area of Rectangle: 24.00
}
}
Method Overriding
• In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to
override the method in the superclass.
• When an overridden method is called from within its subclass, it will always refer to the
version of that method defined by the subclass.
• The version of the method defined by the superclass will be hidden.
class B extends A {
// Method overriding.
int k;
class A {
B(int a, int b, int c) {
int i, j; super(a, b);
A(int a, int b) { k = c;
i = a; }
j = b; // display k – this overrides show() in A
void show() {
}
System.out.println("k: " + k);
// display i and j
}
void show() { }
System.out.println("i and j: " + i + " " class Override {
+ j);
public static void main(String args[]) {
} B subOb = new B(1, 2, 3);
} subOb.show(); // this calls show() in B
}
}
The output produced by this program is shown
here:
k: 3
• When show( ) is invoked on an class B extends A {
object of type B, the version of int k;
show( ) defined within B is used.
B(int a, int b, int c) {
• That is, the version of show( ) inside
super(a, b);
B overrides the version declared in
A. k = c;
• If you wish to access the superclass }
version of an overridden method, void show() {
you can do so by using super.
super.show(); // this calls A's show()
• For example, in this version of B, the System.out.println("k: " + k);
superclass version of show( ) is
invoked within the subclass’ version. }
• This allows all instance variables to }
be displayed.
If you substitute this version of A into the previous program, you will see the
following
output:
i and j: 1 2
k: 3
Static keyword
 Normally, a class member must be accessed only in conjunction with
an object of its class.
 However, it is possible to create a member that can be used by itself,
without reference to a specific instance.
 To create such a member, precede its declaration with the keyword
static. When a member is declared static, it can be accessed before
any objects of its class are created, and without reference to any
object.
 You can declare both methods and variables to be static. The most
common example of a static member is main( ).
 main( ) is declared as static because it must be called before any
objects exist.

 Public static void main()


 Instance variables declared as static are, essentially, global
variables.
 When objects of its class are declared, no copy of a static variable is
made. Instead, all instances of the class share the same static
variable.

Methods declared as static have several restrictions:


 They can only directly call other static methods.
 They can only directly access static data.
 They cannot refer to this or super in any way.
class StaticDemo
{
static int a = 42;
static int b = 99;
static void callme()
{
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
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.
• 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 a superclass reference variable,
different versions of the method are executed.
// Dynamic Method Dispatch
class Dispatch {
class A {
public static void main(String args[]) {
void callme() {
System.out.println("Inside A's callme method");
A a = new A(); // object of type A
} B b = new B(); // object of type B
} C c = new C(); // object of type C
class B extends A { A r; // obtain a reference of type A
// override callme()
• r = a; // r refers to an A object
void callme() {
• r.callme(); // calls A's version of callme
System.out.println("Inside B's callme method");
} • r = b; // r refers to a B object
} • r.callme(); // calls B's version of callme
class C extends A { • r = c; // r refers to a C object
// override callme() • r.callme(); // calls C's version of callme
void callme() {
• }
System.out.println("Inside C's callme method");
• }
}
}
Abstract Classes

• 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 {

abstract class Figure { Triangle(double a, double b) {


super(a, b);
double dim1;
}
double dim2;
// override area for right triangle
Figure(double a, double b) {
double area() {
dim1 = a; System.out.println("Inside Area for Triangle.");
dim2 = b; return dim1 * dim2 / 2;
} }
// area is now an abstract method }
abstract double area(); class AbstractAreas {
} public static void main(String args[]) {

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

Using final to Prevent Overriding


• While method overriding is one of Java’s most powerful features, there will be times
when you will want to prevent it from occurring.
• 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! Can't override.
System.out.println("Illegal!");
}
}
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 {
//...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
//...
}
• As the comments imply, it is illegal for B to inherit A since A is declared as final.
final class A {
final int a =10
//...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
//...
}

You might also like