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

Module-3 Inheritance (1)

The document covers the concept of inheritance in Java, detailing its types such as single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance. It explains the use of the 'super' keyword, method overriding, dynamic method dispatch, and the role of abstract classes in enforcing subclass implementation. Additionally, it provides code examples to illustrate these concepts and their applications in object-oriented programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Module-3 Inheritance (1)

The document covers the concept of inheritance in Java, detailing its types such as single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance. It explains the use of the 'super' keyword, method overriding, dynamic method dispatch, and the role of abstract classes in enforcing subclass implementation. Additionally, it provides code examples to illustrate these concepts and their applications in object-oriented programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

[Type here] [Type here] [Type here]

Module 3
Inheritance
Syllabus:
Inheritance: Inheritance, Using super, Creating a Multilevel Hierarchy, When Constructors Are Called,
Method Overriding, Dynamic Method Dispatch, Using Abstract Classes, Using final with Inheritance, The
Object Class.

3.1 Inheritance
Inheritance is one of the building blocks of object oriented programming languages. It allows creation of
classes with hierarchical relationship among them. Using inheritance, one can create a general class that
defines traits common to a set of related items. This class can then be inherited by other, more specific
classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is
called a superclass. 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 add its own, unique elements. Through inheritance, one can achieve re-usability of the code.

In Java, inheritance is achieved using the keyword extends. The syntax is given below:
class A //super class
{
//members of class A
}

class B extends A //sub class


{
//members of B
}

Consider a program to understand the concept:

class A
{
int i, j;

void showij()
{
System.out.println("i and j: " + i + " " + j);
}
}

class B extends A
{
int k;
void showk()
{
[Type here] [Type here] [Type here]

System.out.println("k: " + k);


}
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}

class SimpleInheritance
{
public static void main(String args[])
{
A superOb = new A();B
subOb = new B();
superOb.i = 10;
superOb.j = 20; System.out.println("Contents of
superOb: ");superOb.showij();

subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");

subOb.showij();
subOb.showk();

System.out.println("Sum of i, j and k in subOb:");subOb.sum();


}
}

Note that, private members of the super class can not be accessed by the sub class. The subclass contains all
non-private members of the super class and also it contains its own set of members to achieve specialization.

3.1.1Type of Inheritance
 Single Inheritance: If a class is inherited from one parent class, then it is known as single
inheritance. This will be of the form as shown below –

superclass

subclass

The previous program is an example of single inheritance.


[Type here] [Type here] [Type here]

 Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also
acts as the base class for other classes. In the below image, class A serves as a base class for the derived
class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access
the grandparent’s members.

 Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the
below image, class A serves as a base class for the derived classes B, C, and D.

 Multiple Inheritance (Through Interfaces)


In Multiple inheritances, one class can have more than one superclass and inherit features from all parent
classes. Please note that Java does not support multiple inheritances with classes. In Java, we can achieve
multiple inheritances only through Interfaces. In the image below, Class C is derived from interfaces A and
B.
[Type here] [Type here] [Type here]

 Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple
inheritances with classes, hybrid inheritance involving multiple inheritance is also not possible with
classes. In Java, we can achieve hybrid inheritance only through Interfaces if we want to involve
multiple inheritance to implement Hybrid inheritance.
However, it is important to note that Hybrid inheritance does not necessarily require the use of
Multiple Inheritance exclusively. It can be achieved through a combination of Multilevel Inheritance
and Hierarchical Inheritance with classes, Hierarchical and Single Inheritance with classes.
Therefore, it is indeed possible to implement Hybrid inheritance using classes alone, without relying
on multiple inheritance type.

3.2 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. Consider the following for illustration:

class Base
{
void dispB()
{
System.out.println("Super class " );
}
}
class Derived extends Base
{
void dispD()
{
System.out.println("Sub class ");
}
}

class Demo
{
public static void main(String args[])
{
Base b = new Base();
[Type here] [Type here] [Type here]

Derived d=new Derived();

b=d; //superclass reference is holding subclass object


b.dispB();
//b.dispD(); error!!
}
}

Note that, the type of reference variable decides the members that can be accessed, but not the type of the
actual object. That is, when a reference to a subclass object is assigned to a superclass reference variable,
you will have access only to those parts of the object defined by the superclass.

Using super
In Java, the keyword super can be used in following situations:
 To invoke superclass constructor within the subclass constructor
 To access superclass member (variable or method) when there is a duplicate member name in
the subclass

Let us discuss each of these situations:


 To invoke superclass constructor within the subclass constructor: Sometimes, we may need to
initialize the members of super class while creating subclass object. Writing such a codein subclass
constructor may lead to redundancy in code. For example,

class Box
{
double w, h, b;

Box(double wd, double ht, double br)


{
w=wd; h=ht; b=br;
}
}
class ColourBox extends Box
{
int colour;
ColourBox(double wd, double ht, double br, int c)
{
w=wd; h=ht; b=br; //code redundancy
colour=c;
}
}

Also, if the data members of super class are private, then we can’t even write such a code in subclass
constructor. If we use super() to call superclass constructor, then it must be the first statement executed
inside a subclass constructor as shown below –

class Box
[Type here] [Type here] [Type here]

{
double w, h, b;
Box(double wd, double ht, double br)
{
w=wd; h=ht; b=br;
}
}

class ColourBox extends Box


{
int colour;
ColourBox(double wd, double ht, double br, int c)
{
super(wd, ht, br); //calls superclass constructor
colour=c;
}
}

class Demo
{
public static void main(String args[])
{
ColourBox b=new ColourBox(2,3,4, 5);
}
}

Here, we are creating the object b of the subclass ColourBox . So, the constructor of this class is invoked.
As the first statement within it is super(wd, ht, br), the constructor of superclass Box is invoked, and then
the rest of the statements in subclass constructor ColourBox are executed.

 To access superclass member variable when there is a duplicate variable name in the subclass:
This form of super is most applicable to situations in which member names of a subclass hide
members by the same name in the superclass.

class A
{
int a;
}

class B extends A
{
int a; //duplicate variable a

B(int x, int y)
{
super.a=x; //accessing superclass a
a=y; //accessing own member a
[Type here] [Type here] [Type here]

void disp()
{
System.out.println("super class a: "+ super.a);
System.out.println("sub class a: "+ a);
}
}

class SuperDemo
{
public static void main(String args[])
{
B ob=new B(2,3);
ob.disp();
}
}

3.20 Creating Multilevel Hierarchy


Java supports multi-level inheritance. A sub class can access all the non-private members of all of its
super classes. Consider an illustration:

class A
{ int a;
}

class B extends A
{ int b;
}

class C extends B
{ int c;

C(int x, int y, int z)


{
a=x; b=y; c=z;
}
void disp()
{
System.out.println("a= "+a+ " b= "+b+" c="+c);
}
}

class MultiLevel
{
public static void main(String args[])
[Type here] [Type here] [Type here]

{
C ob=new C(2,3,4);
ob.disp();
}
}

3.2 When Constructors are called


When class hierarchy is created (multilevel inheritance), the constructors are called in the order of their
derivation. That is, the top most super class constructor is called first, and then its immediate sub class
and so on. If super is not used in the sub class constructors, then the default constructor of super class
will be called.

class A
{
A()
{
System.out.println("A's constructor.");
}
}

class B extends A
{
B()
{
System.out.println("B's constructor.");
}
}

class C extends B
{
[Type here] [Type here] [Type here]

C()
{
System.out.println("C's constructor.");

}
}

class CallingCons
{
public static void main(String args[])

{
C c = new C();
}
}

Output:
A's constructor B's
constructor C's
constructor

3.3 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 a 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 A
{
int i, j; A(int a,
int b)
{
i = a;j =
b;
}
void show() //suppressed
{
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);k =
[Type here] [Type here] [Type here]

c;
}
void show() //Overridden method
{
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show();
}
}

Output:
k: 3

Note that, above program, only subclass method show() got called and hence only k got displayed. That is,
the show() method of super class is suppressed. If we want superclass method also to be called, we can re-
write the show() method in subclass as –

void show()
{
super.show(); // this calls A's show()
System.out.println("k: " + k);
}

Method overriding occurs only when the names and the type signatures of the two methods (one in
superclass and the other in subclass) are identical. If two methods (one in superclass and the other in
subclass) have same name, but different signature, then the two methods are simply overloaded.

3.4 Dynamic Method Dispatch


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. Java implements run-time polymorphism using dynamic method dispatch. We
know that, a superclass reference variable can refer to subclass object. Using this fact, Java resolves the calls
to overridden methods during runtime. 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.
[Type here] [Type here] [Type here]

class A
{
void callme()
{
System.out.println("Inside A");
}
}
class B extends A
{
void callme()
{
System.out.println("Inside B");
}
}

class C extends A
{
void callme()
{

System.out.println("Inside C");
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A();B b
= new B(); C c =
new C();

A r; //Superclass reference
r = a; //holding subclass object
r.callme();r =
b; r.callme();r
= c; r.callme();
}
}

Why overridden methods?


Overridden methods are the way that Java implements the “one interface, multiple methods” aspect of
polymorphism. superclasses and subclasses form a hierarchy which moves from lesser to greater
specialization. Used correctly, the superclass provides all elements that a subclass can use directly. It also
defines those methods that the derived class must implement on its own. This allows the subclass the
flexibility to define its own methods, yet still enforces a consistent interface. Thus, by combining inheritance
with overridden methods, a superclass can define the general form of the methods that will beused by all of
its subclasses. Dynamic, run-time polymorphism is one of the most powerful mechanisms that
[Type here] [Type here] [Type here]

objectoriented design brings to bear on code reuse and robustness.

3.5 Using Abstract Classes


Sometimes, the method definition will not be having any meaning in superclass. Only the subclass
(specialization) may give proper meaning for such methods.In such a situation, having a definition for a
method in superclass is absurd. Also, we should enforce the subclass to override such a method. A method
which does not contain any definition in the superclass is termed as abstract method. Such a method
declaration should be preceded by the keyword abstract. These methods are sometimes referred to as
subclasser responsibility because they have no implementation specified in the superclass.

A class containing at least one abstract method is called as abstract class. Abstract classes can not be
instantiated, that is one cannot create an object of abstract class. Whereas, a reference can be created for an
abstract class.
abstract class A
{
abstract void callme();void
callmetoo()
{
System.out.println("This is a concrete method.");
}
}

class B extends A
{
void callme() //overriding abstract method
{
System.out.println("B's implementation of callme.");
}
}

class AbstractDemo
{
public static void main(String args[])
{
B b = new B(); //subclass object b.callme(); //calling
abstract methodb.callmetoo(); //calling concrete method
}
}

Example: Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeter(). Create subclasses Circle and Triangle that extend the
Shape class and implement the respective methods to calculate the area and perimeter of each
shape(LAB Program)

abstract class Shape {


// Abstract methods to calculate area and perimeter
[Type here] [Type here] [Type here]

public abstract double calculateArea();


public abstract double calculatePerimeter();
}

class Circle extends Shape {


private double radius;

// Constructor for Circle class


public Circle(double radius) {
this.radius = radius;
}

// Implementation of abstract methods for Circle


@Override
public double calculateArea() {
return Math.PI * radius * radius;
}

@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}

class Triangle extends Shape {


private double side1;
private double side2;
private double side3;

// Constructor for Triangle class


public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
[Type here] [Type here] [Type here]

// Implementation of abstract methods for Triangle


@Override
public double calculateArea() {
// Using Heron's formula to calculate the area of a triangle
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

@Override
public double calculatePerimeter() {
return side1 + side2 + side3;
}
}

public class Main {


public static void main(String[] args) {
// Example usage of Circle
Circle circle = new Circle(5.0);
System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Circle Perimeter: " + circle.calculatePerimeter());

System.out.println();

// Example usage of Triangle


Triangle triangle = new Triangle(3.0, 4.0, 5.0);
System.out.println("Triangle Area: " + triangle.calculateArea());
System.out.println("Triangle Perimeter: " + triangle.calculatePerimeter());
}
}

Explanation:

Shape is an abstract class with abstract methods calculateArea() and calculatePerimeter(). These methods will
be implemented by the subclasses.
[Type here] [Type here] [Type here]

Circle is a subclass of Shape with a constructor that takes the radius as a parameter. It implements the abstract
methods calculateArea() and calculatePerimeter() based on the formulas for the area and perimeter of a circle.

Triangle is another subclass of Shape with a constructor that takes the lengths of its three sides as parameters.
It implements the abstract methods calculateArea() and calculatePerimeter() using Heron's formula for the
area and simple addition for the perimeter.

The Main class demonstrates the usage of the Circle and Triangle classes by creating instances of each and
calling their respective methods to calculate area and perimeter.
3.6 Using final
The keyword final can be used in three situations in Java:
3.6.1 To create the equivalent of a named constant.
3.6.2 To prevent method overriding
3.6.3 To prevent Inheritance

To create the equivalent of a named constant: A variable can be declared as final. Doing so prevents its
contents from being modified. This means that you must initialize a final variable when it is declared. For
example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS =
4;final int FILE_QUIT = 5;

It is a common coding convention to choose all uppercase identifiers for final variables. Variables declared
as final do not occupy memory on a per-instance basis. Thus, a final variable is essentially a constant.

To prevent method overriding: Sometimes, we do not want a superclass method to be overridden in


the subclass. Instead, the same superclass method definition has to be used by every subclass. In such
situation, we can prefix a method with the keyword final as shown below –
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!");
}
}

To prevent Inheritance: As we have discussed earlier, the subclass is treated as a specialized class and
superclass is most generalized class. During multi-level inheritance, the bottom most class will be with all
[Type here] [Type here] [Type here]

the features of real-time and hence it should not be inherited further. In such situations, we can prevent a
particular class from inheriting further, using the keyword final. For example –
final class A
{
// ...
}
class B extends A // ERROR! Can't subclass A
{
// ...
}

Note:
3.6.4 Declaring a class as final implicitly declares all of its methods as final, too.
3.6.5 It is illegal to declare a class as both abstract and final since an abstract class is
incomplete byitself and relies upon its subclasses to provide complete implementations

3.7 The Object Class


There is one special class, Object, defined by Java. All other classes are subclasses of Object. That is, Object
is a superclass of all other classes. This means that a reference variable of type Object can referto an object
of any other class. Also, since arrays are implemented as classes, a variable of type Object can also refer to
any array. Object defines the following methods, which means that they are available in every object.

Method Purpose
Object clone( ) Creates a new object that is the same as the object being cloned.

boolean equals(Object object) Determines whether one object is equal to another.


void finalize( ) Called before an unused object is recycled.

Class getClass( ) Obtains the class of an object at run time.


int hashCode( ) Returns the hash code associated with the invoking object.
void notify( ) Resumes execution of a thread waiting on the invoking object.

void notifyAll( ) Resumes execution of all threads waiting on the invoking object.

String toString( ) Returns a string that describes the object.

void wait( ) Waits on another thread of execution.


void wait(long
milliseconds) void wait(long
milliseconds, int
nanoseconds)

The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may override the
others. The equals( ) method compares the contents of two objects. It returns true if the objects are
[Type here] [Type here] [Type here]

equivalent, and false otherwise. The precise definition of equality can vary, depending on the type of
objects being compared. The toString( ) method returns a string that contains a description ofthe object
on which it is called. Also, this method is automatically called when an object is outputusing
println( ). Many classes override this method.

You might also like