You are on page 1of 27

Extending Classes

and Inheritance
Mrs. Apurwa Barve
Inheritance (IMCC)

 Inheritance is one of the basic pillars of OOP.

 Inheritance is achieved by creating a hierarchy of classes such that they are related to
each other through IS-A relationship.

 A more general or broad class is called as a Super class or a Parent class. While a less
general or less broad or specific class is called as a Sub class or a Child class.

 A super/parent class can have multiple sub classes a sub/child class can directly have
only one super class.

 This linking between a sub class and a super class is established by using the keyword
‘extends’. Such as, the child class extends a parent class.

 By extending a parent class, the child class gets ALL the properties and behavior of its
parent class. Thus inheritance helps in re-use of data members.
Mrs. Apurwa Barve
Inheritance (IMCC)

 Consider this, HumanBeing, Dog, Whale are all Mammals. They show common behavior of
mammals plus their own specialized behavior. Hence we can say that,

Mammal

IS-A
HumanBeing Dog Whale

 Let’s put this programmatically to understand how inheritance works in Java.


Mrs. Apurwa Barve
Inheritance Implementation (IMCC)

 We will start by writing Mammals class and defining some instance variables and methods
within it.
class Mammals This is our Super
{ class
String species;
String habitat;
int age;

public void makeSound()


{
System.out.println("Mammals make some sound");
}
public void eatFood()
{
System.out.println("Mammals eat food");
}
public void live()
{
System.out.println("Mammals live on ground and trees and water");
}

}
Mrs. Apurwa Barve
Inheritance Implementation (IMCC)

 We will write HumanBeing class now.

class HumanBeing
{ Properties and method specific
String nationality; to HumanBeing class.
String name;

public void read(){


System.out.println(“I can read”);
}
}

 Let’s link HumanBeing to Mammals through inheritance. For this we use the keyword,
‘extends’
class HumanBeing extends Mammals

HumanBeing IS-A Mammal


Mrs. Apurwa Barve
Inheritance Implementation (IMCC)

HumanBeing class will now inherit properties and methods of Mammals class and look like :
class HumanBeing extends Mammals
{
String species; Properties of Mammals class are inherited
String habitat; in addition to properties of HumanBeing
int age; class
String nationality;
String name;
public void makeSound()
{
System.out.println("Mammals make some sound");
}
public void eatFood() Methods (behavior) of
{ Mammals class are
System.out.println("Mammals eat food"); inherited in addition to
} methods of HumanBeing
public void live() class
{
System.out.println("Mammals live on ground and trees and water");
}
public void read(){
System.out.println(“I can read”);
}
}
Mrs. Apurwa Barve
Invoking super class, sub class methods & variables (IMCC)

Let us now create objects of Mammals class (Super class) and HumanBeing class (sub class)
and see how methods are invoked and variables are accessed.
public class InheritanceDemo {
public static void main(String args[]) Creating objects
{ of sub class and
HumanBeing subObj=new HumanBeing(); super class
Mammals superObj = new Mammals();
Accessing
//first check the properties of Mammals
properties and
superObj.eatFood(); superObj.noise(); superObj.live();
behaviour of
System.out.println("Species of mammals :"+superObj.species);
super class
System.out.println("Max life of mammals :"+superObj.max_Age);
System.out.println("Habitat of mammals :"+superObj.habitat);
System.out.println();System.out.println();System.out.println();

//now check the properties of sub class HumanBeing


subObj.eatFood(); subObj.noise(); subObj.live(); Accessing
subObj.read(); methods of
System.out.println("Species of mammals :"+subObj.species); superclass using
System.out.println("Max life of mammals :"+subObj.max_Age); sub class object.
System.out.println("Habitat of mammals :"+subObj.nationality); Also accessing
} the variables of
} sub class.
Mrs. Apurwa Barve
Class Activity 1 (IMCC)

1. As per HumanBeing class, write Dog class and Whale class and link them to Mammals
class. Dog and Whale classes should have at least one property and method of their own
in addition to inherited properties and methods.
Observe that each child class of Mammals get its own copy of properties and methods of
parent class.

2. Using Eclipse, write Mammals, HumanBeing, Dog and Whale classes within Project -
Chap3Prj.
3. Add a class, InheritanceDemo and create objects of super class and sub classes.
Demonstrate how datamembers and methods of these classes are accessed.
Mrs. Apurwa Barve
Types of Inheritance (IMCC)

1. Single Inheritance
This happens when ONE SUB class inherits from ONE PARENT class. This is ONE-TO-ONE
inheritance.

class
Mammal

class
HumanBeing

Consider, previous example where HumanBeing class extends from Mammal class.
Mrs. Apurwa Barve
Types of Inheritance (IMCC)

2. Multilevel Inheritance : This happens when there is a chain of inheritance. Thus one
sub class can have more than one parent classes which are over each other, as shown
below:
class
Mammal
Level 1 of
Inheritance

class
HumanBeing

Level 2 of
Inheritance
class
Employee

In above diagram, Employee class is a SUB class of HumanBeing class which in turn is a SUB
class of Mammal class.
Mrs. Apurwa Barve
Types of Inheritance (IMCC)

3. Hierarchical Inheritance : This happens when two or more classes inherit from the same
class.
class
Mammal

class
class Whale
HumanBeing

In above diagram, HumanBeing class inherits from Mammal just like Whale class inherits
from Mammal. Thus, parent class (Mammal) has more than one child classes (HumanBeing
and Whale).
Mrs. Apurwa Barve
Types of Inheritance (IMCC)

Multiple Inheritance :
Multiple inheritance happens when one sub class inherits from more than one parent classes
which are at same level. Consider the case below, HumanBeing inherits from Mammal and
LandDwellers class at the same time. Both parent classes are at the same level.

class class
Mammal LandDwellers

class
HumanBeing

 Java does not support Multiple inheritance to keep the language easy and less
complicated. It also helps in avoiding errors.
 However, using INTERFACES, multiple inheritance can be used in Java.
Mrs. Apurwa Barve
Constructors in Inheritance (IMCC)

 Constructor is called when an object is created. Consider following example to


understand how constructors behave in inherited classes.

ConstructorDemo.java
Mammal.java
HumanBeing.java.
Mrs. Apurwa Barve
super keyword (IMCC)

can be used to refer to immediate parent


class instance variable

can be used to invoke immediate parent class


super method.

super() can be used to invoke immediate


parent class constructor.

To understand how super is used in method overriding watch


methodoverridingwithsuper video
Mrs. Apurwa Barve
Class Activity 2 (IMCC)

1. Write a class Shape. It should have following data members:


Instance variable : name, description,angels
Methods : addDescription(), draw()
Constructor : One non parameterized constructor, one overloaded parameterized
constructor which takes arguments for name and angles and sets them in instance
variables.
2. Write classes, Circle and Square. Inherit these from Shape class. Override addDescription()
and draw() in these sub-classes. Create objects of these class using another class,
ShapeDemo which will have main().
3. Demonstrate use of this() and super() in subclass constructors and overridden methods.
Mrs. Apurwa Barve
Polymorphism in Inheritance (IMCC)

 Self study
 Read
https://www.w3schools.com/java/java_polymorphism.asp#:~:text=Polymorphism%20mea
ns%20%22many%20forms%22%2C,methods%20to%20perform%20different%20tasks.
Mrs. Apurwa Barve
Interfaces (IMCC)

 Interfaces are very much like class but they are not a class and they can not be
instantiated.

 They can have variables and methods. Methods within an interface may be concrete or
without body.

 Interfaces are similar to abstract classes wherein, interfaces are responsibility of


implementing class.

 In order to use an interface, a class needs to use ‘implements’ keyword followed by


interface name.

Syntax :
class classname implements interfacename

 One class can implement more than one interface but can not extend more than one class.
Thus by way of interfaces Java has given a way for multiple inheritance.
Mrs. Apurwa Barve
Steps to write & implement interface (IMCC)

Step1 > Define an interface .

Consider following interface Animal. It can have list of methods and variables. These
methods were strictly without body till Java7. However from Java8 onwards, methods in
interface can be concrete (with body) but they either need to be of access default or they
have to be static.

public interface Animal {

//methods without body

public void sound();


public void diet();

//concrete method – default access


default void habitat()
{
System.out.println(“Place where an animal lives is its habitat”);
}

//concrete static method


static void description()
{
System.out.println(“ All animals belong to class AnimalKingdom”);
}

}
Mrs. Apurwa Barve
Steps to write & implement interface (IMCC)

Step 2 > Define the class(es) wanting to use that interface. Implement the interface within
those classes and override ALL non-concrete methods of that interface.
(Default Concrete methods can be overridden too but that is not a compulsion)

public class Dog implements Animal { Use an interface in your class with
keyword, implements followed by
the name of that interface.
public void sound()
{
System.out.println("I am a Dog and I bark");
}
Overriding ALL non-concrete
public void diet() methods of interface.
{
System.out.println("I am a Dog and I eat Dog food");
}

//not overriding default concrete methods of Animal interface. static methods CANNOT be
overridden.

}
Mrs. Apurwa Barve
Steps to write & implement interface (IMCC)

We will write one more implementing class, Lion.

class Lion implements Animal


{
public void sound()
{
System.out.println("I am a Lion and I roar");
}
public void diet()
{
System.out.println("I am a Lion and I eat other animals");
}

//overriding default concrete method of Animal interface.


default void habitat()
{
System.out.println(“Lion lives in a den”);
}

}
Mrs. Apurwa Barve
Steps to write & implement interface (IMCC)

Step 3 : Create objects of implementing class(es) to call interface methods (overridden or


not)
public class AnimalDemo {
We use the reference of interface
public static void main(String args[]) Animal and create an object of Dog.
{ Animal aniObj = new Dog(); Thus aniObj will point to Dog.
aniObj.diet();
aniObj.sound();
Guess the o/p of these method
aniObj.habitat();
calls.
//calling static method
Animal.description();
Now aniObj is made to point at
aniObj=new Lion();
Lion class object.
aniObj.diet();
aniObj.sound();
aniObj.habitat(); Guess the o/p of these method
//calling static method calls.
Animal.description();

}
}
Mrs. Apurwa Barve
Interface (IMCC)

 Now let us check executable code for previous interface and classes. Refer
Animal.java
Dog.java
Lion.java
AnimalDemo.java

To brush up the concept of interface and its implementation


watch interfacedemo video
Mrs. Apurwa Barve
Class Activity 3 (IMCC)

1. Write an interface Calculator. It should have following methods :


a. Declare following no-body methods
public double add(double n1,double n2);
public double subtract(double n1,double n2);
public double multiply(double n1,double n2);
public double division(double n1,double n2);

b. Declare following concrete method:


public void result(){
//add some print statement here.
}

c. Declare following static method:


static void aboutCalculator(){
//add some print statement here.
}
2. Write an implementing class for above interface. Create its objects and call relevant
methods.
3. For above Calculator, write an abstract class instead of an interface. Add all necessary
methods and provide an implementing class.
Mrs. Apurwa Barve
Type Compatibility and Conversion (IMCC)

 Self study.
 https://www.geeksforgeeks.org/type-conversion-java-examples/
 https://www.infoworld.com/article/3172592/type-dependency-in-java-part-
1.html#:~:text=We%20say%20that%20two%20types,through%20assignment%20or%20par
ameter%20passing.
Mrs. Apurwa Barve
What we learnt? (IMCC)
Mrs. Apurwa Barve
Quiz (IMCC)

 Kindly take the quiz of this chapter to assess your knowledge of concepts covered in this
chapter.
Thank you!

You might also like