CHP 4 Inheritance

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Chp 4.

Inheritance
Inheritance in java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//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.
1.Single Inheritance
1) Single Inheritance
Single inheritance is damn easy to understand. When a class
extends another one class only then we call it a single inheritance.
The below flow diagram shows that class B extends only one class
which is A. Here A is a parent class of B and B would be a child class
of A.
Multilevel Inheritance
2) 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. For more details and example refer –
Multilevel inheritance in Java.
3.Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending
(Or inherits) more than one base class. The inheritance we learnt
earlier had the concept of one base class or parent. The problem
with “multiple inheritance” is that the derived class will have to
manage the dependency on two base classes.
4.Hierarchical Inheritance

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.
Read More at – Hierarchical Inheritance in java with example program.
5.Hybrid Inheritance

Hybrid Inheritance
In simple terms you can say that 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!! Using interfaces.
yes you heard it right. By using interfaces you can have multiple as well as hybrid
inheritance in Java.
class room
{
int l; Compilation and Execution:
int b;
room(int x, int y)
{ javac inheritance.java
l=x;
b=y; java inheritance
}
int area()
{
return(l*b); OUTPUT:
} area1=200
}
class bedroom extends room volume1=6000
{
int h;
bedroom(int x,int y, int z)
{
super(x,y);
h=z;
}
int volume()
{
return(l*b*h);
}
}
class inheritance
{
public static void main(String args[])
{
bedroom room1=new
bedroom(10,20,30);
int area1=room1.area();
int volume1=room1.volume();
System.out.println("area1="+area1);
System.out.println("volume1="+volume1);
}
}
super keyword
• 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:
➢ Use of super with variables:
➢ Use of super with methods:
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. We can
understand it more clearly using this code snippet:
Use of super with variables:
/* Base class vehicle */
class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
/* Driver program to test */
class Test
{
public static void main(String[] args) Maximum Speed:120
{
Car small = new Car();
small.display();
}
}
In the above example, both base class and subclass have a member maxSpeed. We
could access maxSpeed of base class in sublcass using super keyword.
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 resolve ambiguity we use super
keyword. This code snippet helps to understand the said
usage of super keyword.
Use of super with methods:
/* Base class Person */
class Person
{
void message()
{
System.out.println("This is person class");
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
message();
OUTPUT:
super.message();
} This is student class
} This is person class
/* Driver program to test */
class Test
{
public static void main(String args[])
{
Student s = new Student();
s.display();
}
}
Final Keyword In Java
The final keyword in java is used to restrict the user. The java
final keyword can be used in many context. Final can be:
• variable
• method
• class
The final keyword can be applied with the variables, a final
variable that have no value it is called blank final variable or
uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be
initialized in the static block only. We will have detailed learning
of these. Let's first learn the basics of final keyword.
1) Java final variable

• If you make any variable as final, you


cannot change the value of final variable(It
will be constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value
can never be changed.
class Bike9
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
OUTPUT:
obj.run();
Compile Time Error
}
}//end of class
2) Java final method

If you make any method as final, you cannot


override it.
Example of final method
class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{ OUTPUT:
Compile Time Error
Honda honda= new Honda();
honda.run();
}
}
3) Java final class
If you make any class as final, you cannot extend it.

final class Bike{}


class Honda1 extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda1 honda= new Honda1();
OUTPUT:
honda.run(); Compile Time Error
}
}
Abstract Class and Abstract Methods
A class which is declared with the abstract keyword is known as an abstract
class in Java. It can have abstract and non-abstract methods

Abstraction in Java

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.
Abstract Class and Abstract Methods

Abstract class in Java


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.

Abstract Method in Java


A method which is declared as abstract and does not have
implementation is known as an abstract method.
abstract class Bank
{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class PNB extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
OUTPUT:
class TestBank Rate of Interest is: 7 %
{ Rate of Interest is: 8 %
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
Method Overriding

Declaring a method in sub class which is


already present in parent class is known as
method overriding. Overriding is done so
that a child class can give its own
implementation to a method which is already
provided by the parent class. In this case the
method in parent class is called overridden
method and the method in child class is
called overriding method.
Method Overriding Example
class Human
{
//Overridden method
public void eat()
{
System.out.println(“The Human is eating");
}
}
class Boy extends Human
{
//Overriding method
public void eat()
{
System.out.println(“The Boy is eating");
}
public static void main( String args[]) { OUTPUT:
Boy is eating
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Method Overriding Example
class college
{
public void move()
{
System.out.println("College is open");
}
}
class univ extends college
{
public void move()
{
System.out.println("University is open too");
}
}
public class stud
{
public static void main(String args[])
{ OUTPUT:
college a = new college(); College is open
college b = new univ(); University is open too
a.move();
b.move();
}
}
Java Interface Example: Drawable
//Interface declaration: by first user
interface Drawable
{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println("drawing circle");
}
}
//Using interface: by third user
class TestInterface1
{
public static void main(String args[])
{
Drawable d=new Circle();
d.draw();
}
}
Java Interface Example: Drawable
In this example, the Drawable interface has only one method. Its implementation is
provided by Rectangle and Circle classes. In a real scenario, an interface is defined by
someone else, but its implementation is provided by different implementation
providers. Moreover, it is used by someone else. The implementation part is hidden by
the user who uses the interface.
Java Interface Example: Bank
interface Bank
{
float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest()
{
return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
return 9.7f;
}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}
Multiple inheritance in Java by interface

If a class implements multiple interfaces, or


an interface extends multiple interfaces, it is
known as multiple inheritance.
Multiple Inheritance in Java
Multiple inheritance is not supported through class in java, but it is
possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of
ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its
implementation is provided by the implementation class. For example:

interface Printable
{
void print();
}
interface Showable
{
void print();
}

class TestInterface3 implements Printable, Showable


{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
Like a class, an interface can have methods and variables, but the methods declared in
interface are by default abstract (only method signature, no body).

Interfaces specify what a class must do and not how. It is the blueprint of the class.
An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies a set of
methods that the class has to implement.
If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then class must be declared abstract.

Why do we use interface ?

It is used to achieve total abstraction.


Since java does not support multiple inheritance in case of class, but by using interface it
can achieve multiple inheritance .
interface int1
{
final int a = 10;
void display();
}

public class testClass implements int1


{
public void display()
{
System.out.println("Geek");
}
// Driver Code
public static void main (String[] args)
{
testClass t = new testClass();
t.display();
System.out.println(a);
}
}

You might also like