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

Java Inheritance

The document discusses different types of inheritance in Java including single, multilevel, multiple, hierarchical and hybrid inheritance. It provides code examples to demonstrate each type of inheritance and how inheritance allows classes to inherit properties and behaviors from other classes.

Uploaded by

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

Java Inheritance

The document discusses different types of inheritance in Java including single, multilevel, multiple, hierarchical and hybrid inheritance. It provides code examples to demonstrate each type of inheritance and how inheritance allows classes to inherit properties and behaviors from other classes.

Uploaded by

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

Inheritance in Java

LO3: Demonstrate how to extend java classes and achieve reusability


using Inheritance, Interface and Packages
Inheritance -feature of Object-Oriented Programming

• Inheritance allows a class to use the properties and


methods of another class.

• In other words, the derived class inherits the states and


behaviors from the base class.

• The derived class is also called subclass and the base class is
also known as super-class.

• The derived class can add its own additional variables and
methods.
Inheritance

• These additional variable and methods differentiates the


derived class from the base class.
• Inheritance is a compile-time mechanism.
• A super-class can have any number of subclasses.
• But a subclass can have only one superclass.
• This is because Java does not support multiple inheritance.
• The superclass and subclass have “is-a” relationship
between them
Extends keyword

• The keyword used for inheritance is extends.

Syntax:
public class ChildClass extends BaseClass {
// derived class methods extend and possibly override
}
Example
// A subclass which extends for vehicle
// A class to display the class Car extends Vehicle {
attributes of the vehicle int CC;
class Vehicle { int gears;
void attributescar() {
String color;
// The subclass refers to the
int speed; members of the superclass
int size; System.out.println("Color of Car : " +
void attributes() { color);
System.out.println("Speed of Car : "
System.out.println("Color + speed);
: " + color);
System.out.println("Size of Car : " +
System.out.println("Speed size);
: " + speed); System.out.println("CC of Car : " +
System.out.println("Size : CC);
" + size); System.out.println("No of gears of
} Car : " + gears);
}
} }
public class Test {
public static void main(String args[]) {
Car b1 = new Car();
b1.color = "Blue"; The output is
b1.speed = 200 ;
b1.size = 22; Color of Car : Blue
b1.CC = 1000; Speed of Car : 200
b1.gears = 5; Size of Car : 22
CC of Car : 1000
b1.attributescar();
No of gears of Car : 5
}
}
class Teacher Output:
{
String designation = "Teacher"; XIE
String collegeName = “XIE"; Teacher
void does() Physics
{ Teaching
System.out.println("Teaching");
}
}

public class PhysicsTeacher extends Teacher


{
String mainSubject = "Physics";
public static void main(String args[])
{
PhysicsTeacher obj = new PhysicsTeacher();
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}
• The derived class inherits all the members and methods that are
declared as public or protected.

• If declared as private it can not be inherited by the derived classes.

• The private members can be accessed only in its own class.

• The derived class cannot inherit a member of the base class if the
derived class declares another member with the same name.
Example of member access in Inheritance
Constructors and Inheritance
Output:
class ParentClass{
//Parent class constructor Constructor of Parent
ParentClass(){ Constructor of Child
System.out.println("Constructor of Parent");
}
}
class JavaExample extends ParentClass{
JavaExample(){
/* It by default invokes the constructor of parent class
* You can use super() to call the constructor of parent.
* It should be the first statement in the child class
* constructor, you can also call the parameterized constructor
* of parent class by using super like this: super(10), now
* this will invoke the parameterized constructor of int arg
*/
System.out.println("Constructor of Child");
}
public static void main(String args[]) {
//Creating the object of child class
new JavaExample();
}
}
Types of Inheritance
• Single inheritance
• Multilevel inheritance
• Multiple inheritance
• Hybrid inheritance
• Hierarchical inheritance
Single Inheritance
• Single inheritance is easy to understand.
• When a class extends another one class only then we call it
a single inheritance.
• Here A is a parent class of B and B would be a child class of
A.
Single Inheritance example program in Java

Class A
{
public void methodA()
{
System.out.println("Base class method");
}}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
o/p: Base class method
Child class method
Multiple Inheritance

• Multiple Inheritance refers to the concept of one class


extending (Or inherits) more than one base class.
• The problem with “multiple inheritance” is that the derived
class will have to manage the dependency on two base
classes.
Note

• Multiple Inheritance is very rarely used in software projects.


• Using Multiple inheritance often leads to problems in the
hierarchy.
• This results in unwanted complexity when further extending
the class.
• Most of the new OO languages like Small Talk, Java, C# do
not support Multiple inheritance.
Multiple Inheritance is supported in C++.
Multilevel Inheritance

• Multilevel inheritance refers to a mechanism in OO


technology where one can inherit from a derived class,
thereby making this derived class the base class for the
new class.
• As you can see in below flow diagram C is subclass or child
class of B and B is a child class of A.
Multilevel Inheritance

• Multilevel inheritance there is a concept of grand


parent class.

• If we take the example of above diagram then class


C inherits class B and class B inherits class A which
means B is a parent class of C and A is a parent class
of B.

• So in this case class C is implicitly inheriting the


properties and method of class A along with B that’s
what is called multilevel inheritance.
Multilevel Inheritance example program in Java
Class X //Base Class
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X // Derived Class
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y // sub class of derived
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
Three classes – Car, Maruti and Maruti800.
Class Maruti extends Car and class Maurit800 extends Maurti.
With the help of this Multilevel hierarchy setup our Maurti800 class is able to use
the methods of both the classes (Car and Maruti).

class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti() public class Maruti800 extends Maruti{
{
System.out.println("Class public Maruti800()
Maruti"); {
}
System.out.println("Maruti Model: 800");
public void brand()
}
{ public void speed()
System.out.println("Brand: {
Maruti");
} System.out.println("Max:
public void speed() 80Kmph");
}
{
System.out.println("Max:
90Kmph");
}
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph
Hierarchical Inheritance

• In such kind of inheritance one class is inherited by many


sub classes.
• In below example class B,C and D inherits the same class A.
• A is parent class (or base class) of B,C & D.
Example - Hierarchical
Class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
Class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
Class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
Class MyClass
{
public void methodB()
{
System.out.println("method of Class B");
}
public static void main(String args[])
{
B obj1 = new B(); // creating 3 objects and instantiating
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj2.methodA(); output would be –
obj3.methodA(); method of Class A
method of Class A
} method of Class A
}
Hybrid Inheritance
• Hybrid inheritance is a combination of Single and
Multiple inheritance.
• A typical flow diagram would look like below.
• A hybrid inheritance can be achieved in the java in
a same way as multiple inheritance can be!!
• By using Interfaces you can have multiple as well as
hybrid inheritance in Java.
Note
• Using classes: If in above figure B and C are classes then
this inheritance is not allowed as a single class cannot
extend more than one class (Class D is extending both B
and C). Multiple Inheritance not allowed

• Using Interfaces: If B and C are interfaces then the above


hybrid inheritance is allowed as a single class can
implement any number of interfaces in java.
Method Overriding
• Declaring a method in subclass which is already present
in parent class is known as method overriding

Example:
• One of the simplest example- Boy class
extends Human class.
• Both the classes have a common method void eat().
• Boy class is giving its own implementation to
the eat() method or in other words it is overriding the
method eat().
class Human{
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
Output:
obj.eat();
Boy is eating
}
}
Rules of method overriding in Java

• Argument list:

✓ The argument list of overriding method must be same as


that of the method in parent class.
✓ The data types of the arguments and their sequence
should be maintained as it is in the overriding method.
Rules of method overriding in Java

• Access Modifier:
✓ The Access Modifier of the overriding method (method of
subclass) cannot be more restrictive than the overridden
method of parent class.

✓ For e.g. if the Access Modifier of base class method is


public then the overriding method (child class method )
cannot have private, protected and default Access modifier
as all of the three are more restrictive than public.
class MyBaseClass{
public void disp()
{
System.out.println("Parent class method");
}
}
class MyChildClass extends MyBaseClass{
protected void disp(){
System.out.println("Child class method");
}
public static void main( String args[]) {
MyChildClass obj = new MyChildClass();
obj.disp();
}
}
Error !!!!
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation
problem: Cannot reduce the visibility of the inherited method
from MyBaseClass

This is not allowed as child class disp method is more


restrictive(protected) than base class(public)
However this is perfectly valid scenario as public is less restrictive than protected. Same
access modifier is also a valid one.

class MyBaseClass{
protected void disp() {
System.out.println("Parent class method");
Output:
}
}
Child class
class MyChildClass extends MyBaseClass{ method
public void disp(){
System.out.println("Child class method");
}
public static void main( String args[]) {
MyChildClass obj = new MyChildClass();
obj.disp();
}}
Super keyword in Overriding

• super keyword is used for calling the parent class


method/constructor.

• super.methodname() calling the specified method of base


class while super() calls the constructor of base class.

• Let’s see the use of super in Overriding.


class ABC{
public void mymethod()
{
System.out.println("Class ABC: mymethod()");
}
} Output:
Class ABC: mymethod()
class Test extends ABC{
Class Test: mymethod()
public void mymethod(){
super.mymethod(); //This will call the mymethod() of parent class
System.out.println("Class Test: mymethod()");
}
public static void main( String args[]) {
Test obj = new Test();
obj.mymethod();
}}
Overloading vs overriding
Overloading Overriding
Overloading happens at compile- Overriding happens at runtime
time
The binding of overloaded method Binding of overridden method call
call to its definition happens at to its definition happens at runtime
compile-time
Static methods can be overloaded Static methods cannot be
which means a class can have more overridden, even if you declare a
than one static method of same same static method in child class it
name has nothing to do with the same
method of parent class.
Argument list should be different Argument list should be same in
while doing method overloading. method Overriding.
Overloading Overriding
Basic difference is that For overriding base and child
overloading is being done in the classes are required. Overriding is
same class all about giving a specific
implementation to the inherited
method of parent class.
Static binding is being used for Dynamic binding is being used
overloaded methods for overridden/overriding
methods.
Return type of method does not The overriding method can have
matter in case of method more specific return type
overloading, it can be same or
different
Example of Java Method Overriding
• Consider a scenario,
Bank is a class that provides functionality to get rate of interest.
But, rate of interest varies according to banks. For example, SBI,
ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.
class Bank{
int getRateOfInterest(){return 0;}
}

class SBI extends Bank{


int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Dynamic Method Dispatch or (Runtime
Polymorphism in Java)

• Method overriding is one of the ways in which Java supports


Runtime Polymorphism. Dynamic method dispatch is the
mechanism by which a call to an overridden method is resolved at
run time, rather than compile time.

• When an overridden method is called through a superclass


reference, Java determines which version (superclass/subclasses)
of that method is to be executed based upon the type of the
object being referred to at the time the call occurs. Thus, this
determination is made at run time.
Dynamic Method Dispatch or (Runtime
Polymorphism in Java)
• At run-time, it depends on 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
• A superclass reference variable can refer to a subclass
object. This is also known as upcasting. Java uses this fact to
resolve calls to overridden methods at run time.
Dynamic Method Dispatch or (Runtime
Polymorphism in Java) example
// A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}

class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}
Dynamic Method Dispatch or (Runtime
Polymorphism in Java) example
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}

// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();

// object of type B
B b = new B();

// object of type C
C c = new C();
Dynamic Method Dispatch or (Runtime
Polymorphism in Java) example
// obtain a reference of type A
A ref;

// ref refers to an A object


ref = a;

// calling A's version of m1()


ref.m1();

// now ref refers to a B object


ref = b;

// calling B's version of m1()


ref.m1();

// now ref refers to a C object


ref = c;

// calling C's version of m1()


ref.m1();
}
}
Dynamic Method Dispatch or (Runtime
Polymorphism in Java) example

OUTPUT :

Inside A's m1 method


Inside B's m1 method
Inside C's m1 method
Experiment 9

• Create a Teacher class and derive Professor / Associate Professor /


Assistant Professor class from Teacher class. Define appropriate
constructor for all the classes. Also define a method to display
information of Teacher. Make necessary assumptions as required
Experiment 10

• Consider a hierarchy, where a sportsperson can either be an athlete


or a hockey player. Every sportsperson has a unique name. An athlete
is characterized by the event in which he/she participates; whereas a
hockey player is characterised by the number of goals scored by
him/her.
• Perform the following tasks using Java :
(i)Create the class hierarchy with suitable instance variables and methods.
(ii) Create a suitable constructor for each class.
(iii) Create a method named display_all_info with suitable parameters. This
method should display all the information about the object of a class.
(iv) Write the main method that demonstrates polymorphism.
Assignment 3: Q.1

Q.8 Create a class Book and define a display method to display book
information. Inherit Reference_Book and Magazine classes from Book
class and override display method of Book class in Reference_Book and
Magazine classes. Make necessary assumptions required
Assignment 3: Q.2

Q.9 A university has two types of students — graduate students and research
students. The University maintains the record of the name, age and
programme of every student. For graduate students, additional information
like percentage of marks and stream, like science, commerce, etc. is recorded;
whereas for research students, additionally, specialization and years of
working experience, if any, is recorded. Each class has a constructor. The
constructor of subclasses makes a call to the constructor of the superclass.
Assume that every constructor has the same number of parameters as the
number of instance variables. In addition, every subclass has a method that
may update the instance variable values of that subclass. All the classes have a
function display_student_info( ), the subclasses must override this method of
the base class. Every student is either a graduate student or a research
student.
Perform the following tasks for the description given above using Java :
(i) Create the three classes with proper instance variables and methods,
with suitable inheritance.
(ii) Create at least one parameterised constructor for each class.
(iii) Implement the display_student_info( ) method in each class

You might also like