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

Module-2 Inheritance

Uploaded by

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

Module-2 Inheritance

Uploaded by

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

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.
• Inheritance represents the IS-A relationship which is
also known as a parent-child relationship.
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: 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.
How to use inheritance in Java
• The keyword used for inheritance is extends.
Syntax :
class derived-class extends base-class
{
//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.
Example
class Animal {
// methods and fields
}
class Dog extends Animal {

// methods and fields of Animal


// methods and fields of Dog
}

In the above example, the Dog class is created by inheriting the


methods and fields from the Animal class.
Here, Dog is the subclass and Animal is the superclass
• OOPs support the five different types of
inheritance as given below :
– Single inheritance
– Multi-level inheritance
– Hierarchical Inheritance
– Multiple inheritance
– Hybrid Inheritance
Single Inheritance

• When a class inherits another class, it is known as a single


inheritance. In the example given below, Dog class inherits
the Animal class, so there is the single inheritance.
Example:
class Animal{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class TestInheritance{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}
Multilevel Inheritance
• When there is a chain of
inheritance, it is known as multilevel
inheritance.
class Animal{ As you can see in the
void eat(){ example given below,
System.out.println("eating..."); BabyDog class inherits
} the Dog class which
} again inherits the Animal
class Dog extends Animal{ class, so there is a
void bark(){ multilevel inheritance.
System.out.println("barking...");
}
}
class BabyDog extends Dog{
void weep(){
System.out.println("weeping...");
}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Hierarchical Inheritance
• When two or more classes inherits a single
class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes
inherits the Animal class, so there is hierarchical
inheritance.
Multiple inheritance
• To reduce the complexity and simplify the language, multiple
inheritance is not supported in java.
• Consider a scenario where A, B, and C are three classes. The C class
inherits A and B classes. If A and B classes have the same method
and you call it from child class object, there will be ambiguity to
call the method of A or B class.
Cont.

• Since compile-time errors are better than runtime errors, Java renders compile-
time error if you inherit 2 classes. So whether you have same method or
different, there will be compile time error.
Hybrid Inheritance
• Hybrid (mixture) is made of more than one thing. In
Java, the hybrid inheritance is the composition of
two or more types of inheritance.
A conceptual depiction of the Triangle class

Even though TwoDShape is a superclass for Triangle, it is also a completely


independent, stand-alone class. Being a superclass for a subclass does not mean
that the superclass cannot be used by itself. For example, the following is
perfectly valid:

an object of TwoDShape has no knowledge of or access to any subclasses


of TwoDShape.
• The general form of a class declaration that inherits a superclass is shown
here:

• You can specify only one superclass for any subclass that you create. Java
does not support the inheritance of multiple superclasses into a single subclass.

•A major advantage of inheritance is that once you have created a superclass


that defines the attributes common to a set of objects, it can be used to create
any number of more specific subclasses.
Member Access and Inheritance
• an instance variable of a class will be declared
private to prevent its unauthorized use or
tampering.
• Inheriting a class does not overrule the
private access restriction. Thus, even though a
subclass includes all of the members of its
superclass, it cannot access those members of
the superclass that have been declared private.
Cont…
•The Triangle class will not compile because the reference to width and
height inside the area( ) method causes an access violation.

• Since width and height are declared private, they are accessible only
by other members of their own class. Subclasses have no access to them.

• Remember that a class member that has been declared private will
remain private to its class. It is not accessible by any code outside its
class, including subclasses.

• Java programmers typically use accessor methods to provide access to


the private members of a class. Here is a rewrite of the TwoDShape and
Triangle classes that uses methods to access the private instance
variables width and height:
Constructors and Inheritance
• In a hierarchy, it is possible for both superclasses and subclasses to
have their own constructors. This raises an important question: What
constructor is responsible for building an object of the subclass— the
one in the superclass, the one in the subclass, or both?

• The answer is this: The constructor for the superclass constructs


the superclass portion of the object, and the constructor for the
subclass constructs the subclass part. This makes sense because the
superclass has no knowledge of or access to any element in a subclass.
Thus, their construction must be separate.
When only the subclass defines a constructor, the process is
straightforward: simply construct the subclass object. The superclass
portion of the object is constructed automatically using its default
constructor.
Cont..
Here, Triangle’s constructor initializes the members of TwoDClass
that it inherits along with its own style field.
• When both the superclass and the subclass define constructors, the
process is a bit more complicated because both the superclass and
subclass constructors must be executed.
• In this case, you must use another of Java’s keywords, super, which
has two general forms.

•The first calls a superclass constructor.

•The second is used to access a member of the superclass that has been
hidden by a member of a subclass.
Using super to Call Superclass Constructors

A subclass can call a constructor defined by its


superclass by use of the following form of super:

super(parameter-list);

Here, parameter-list specifies any parameters needed by


the constructor in the superclass.
super( ) must always be the first statement executed
inside a subclass constructor.
Example 1:
class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
}
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}}
Example 2 :
Cont..
• Triangle( ) calls super( ) with the parameters w and
h. This causes the TwoDShape( ) constructor to be
called, which initializes width and height using these
values.
• Triangle no longer initializes these values itself. It
need only initialize the value unique to it: style.
• Any form of constructor defined by the superclass
can be called by super( ).
• The constructor executed will be the one that matches
the arguments.
• For example, here are expanded versions of both
TwoDShape and Triangle that include default
constructors and constructors that take one argument:
Using super to Access Super class Members
• We can use super keyword to access the hidden data member
and method of parent class. It is used if parent class and child
class have same fields.
• This usage has the following general form:
super.member
Here, member can be either a method or an instance variable.

Note: super() is added in each class constructor automatically by


compiler if there is no super() or this().
Example 1:
Creating a Multilevel Hierarchy
• Multilevel Hierarchy allows you to inherit properties
of a grandparent in a child class.
• Given three classes called A, B, and C, C can be a
subclass of B, which is a subclass of A.
• When this type of situation occurs, each subclass
inherits all of the traits found in all of its superclasses.
In this case, C inherits all aspects of B and A.
Example Program 1

class A { public class Demo {


void funcA() { public static void
System.out.println("This is class A"); main(String args[]) {
} C obj = new C();
obj.funcA();
}
obj.funcB();
class B extends A { obj.funcC();
void funcB() { }
System.out.println("This is class B"); }
}
}
class C extends B {
void funcC() {
System.out.println("This is class C");
}
}
Example program 2

class student
{ class marks extends student
int rollno; {
String name; int total;
marks(int r, String n, int t)
student(int r, String n) {
{ super(r,n);
rollno = r; total = t;
name = n; }
} void dispdatam()
void dispdatas() {
{ dispdatas();
System.out.println("Rollno = " + System.out.println("Total = " + total);
rollno); }
System.out.println("Name = " + }
name);
}
}
Cont..

class percentage extends marks class Multi_Inhe


{ {
int per; public static void main(String args[])
{
percentage(int r, String n, int t, int p) percentage stu = new
{ percentage(102689, "RATHEESH", 350,
super(r,n,t); 70);
per = p; stu.dispdatap();
} }
void dispdatap() }
{
dispdatam();
System.out.println("Percentage = "
+ per);
}
}
When Are Constructors Executed?

• When a subclass object is created, whose constructor is


executed first, the one in the subclass or the one defined
by the superclass?
• For example, given a subclass called B and a superclass
called A, is A’s constructor executed before B’s, or vice
versa?
• The answer is that in a class hierarchy, constructors
complete their execution in order of derivation, from
superclass to subclass.
• Further, since super( ) must be the first statement
executed in a subclass’ constructor, this order is the same
whether or not super( ) is used.
• If super( ) is not used, then the default constructor of
each superclass will be executed.
The following program illustrates when constructors are
executed:
Superclass References and Subclass Objects

• Java is a strongly typed language.


• Aside from the standard conversions and
automatic promotions that apply to its
primitive types, type compatibility is strictly
enforced.
• Therefore, a reference variable for one class
type cannot normally refer to an object of
another class type
A reference variable of a superclass can be assigned a reference to an
object of any subclass derived from that superclass. In other words, a
superclass reference can refer to a subclass object.
Method Overriding

• In a class hierarchy, when a method in a


subclass has the same return type and
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.
Cont..

• When show( ) is invoked on an object of type


B, the version of show( ) defined within B is
used.
• That is, the version of show( ) inside B
overrides the version declared in A.
• If you want to access the superclass version of
an overridden method, you can do so by using
super.
For example, in this version of B, the superclass version
of show( ) is invoked within the subclass’ version. This
allows all instance variables to be displayed.
Overridden Methods Support Polymorphism
• Method overriding forms the basis for one of Java’s most powerful
concepts Dynamic Method Dispatch.
• 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.
• 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.
Using Abstract Classes
• Abstraction is a process of hiding the implementation
details and showing only functionality to the user.
• Another way, it shows only essential things to the user
and hides the internal details, for example, sending SMS
where you type the text and send the message. You don't
know the internal processing about the message delivery.
• Abstraction lets you focus on what the object does
instead of how it does it.
• Ways to achieve Abstraction
1. Abstract class
2. Interface
A class which is declared as abstract is known as an abstract
class. It can have abstract and non-abstract methods. It needs to
be extended and its method implemented. It cannot be
instantiated.
Example of abstract class
abstract class A{}
• Abstract Method in Java
• A method which is declared as abstract and does not
have implementation is known as an abstract method.
• Example of abstract method

abstract void printStatus();//


no method body and abstract
Example of Abstract class that has an abstract
method
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike{
void run()
{
System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Example 2:

abstract class Shape{


abstract void draw();
}

class Rectangle extends Shape{


void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
r
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();
s.draw();
}
}
Example of an abstract class that has abstract and non-
abstract methods
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Example 3:

// Using abstract methods and classes. class AbstractAreas {


abstract class Figure { public static void main(String args[]) {
double dim1; // Figure f = new Figure(10, 10); // illegal
double dim2; now
Figure(double a, double b) { Rectangle r = new Rectangle(9, 5);
dim1 = a; Figure figref; // this is OK, no object is
dim2 = b; created
} figref = r;
// area is now an abstract method System.out.println("Area is " +
abstract double area(); figref.area());
} }
class Rectangle extends Figure { }
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for
Rectangle.");
return dim1 * dim2;
}
}
Using final with Inheritance
• The keyword final has three uses.
• First, it can be used to create the equivalent of
a named constant.
• The other two uses of final apply to
inheritance.
Using final with Inheritance
Using final to Prevent Inheritance
Using final with Data Members

class Gfg{
static final int CAPACITY = 4;

public static void main(String args[])


{
// re-assigning final variable
// will throw compile-time error
CAPACITY = 5;
}
}
The Object Class

You might also like