Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
12 views32 pages

Inheritance & Method Overriding

Uploaded by

adithapa129
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views32 pages

Inheritance & Method Overriding

Uploaded by

adithapa129
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT-I

JAVA PROGRAMMING
Dr. Himani Maheshwari
INHERITANCE & METHOD
OVERRIDING
DR. HIMANI MAHESHWARI
ASSISTANT PROFESSOR
SOC
INHERITANCE
• Inheritance is an object-oriented programming concept in which one class
acquires the properties and behavior of another class.
• It represents a parent-child relationship between two classes. This parent-
child relationship is also known as an IS-A relationship.
• Inheritance would give us reusability.
• Another use of inheritance is that using inheritance method overriding can
be achieved ( run time polymorphism).
• 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.
is-a relationship
In Java, inheritance is an is-a relationship. That is, we use inheritance only if
there exists an is-a relationship between two classes. For example,

 Car is a Vehicle
 Orange is a Fruit
 Surgeon is a Doctor
 Dog is an Animal

Here, Car can inherit from Vehicle, Orange can inherit from Fruit, and so on.
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: As the name specifies, 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.
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.
Type of Inheritance
Type of Inheritance

Note: Multiple inheritance is not supported in Java through class .


1. Single Inheritance
When a class inherits another class, class Test {
it is known as a single public static void main(String args[])
inheritance. In the example given
{
below, Dog class inherits the Animal
class, so there is the single Dog d=new Dog();
inheritance.
d.bark();
class Animal{
d.eat();
void eat()
}}
{
OUTPUT:
System.out.println("eating...");}
barking...
}
eating...
class Dog extends Animal{
void bark()
{System.out.println("barking...");}
2. Multilevel Inheritance
When there is a chain of class BabyDog extends Dog{
inheritance, it is known as multilevel Voidweep()
inheritance. As you can see in the {System.out.println("weeping...");}
example given below, BabyDog
class inherits the Dog class which }
again inherits the Animal class, so class Test {
there is a multilevel inheritance.
public static void main(String args[]){
class Animal{
void eat() BabyDog d=new BabyDog();
{System.out.println("eating...");}
d.weep();
}
d.bark();
class Dog extends Animal{
d.eat(); }}
void bark()
{System.out.println("barking...");} OUTPUT:
} weeping... barking... eating...
3. Hierarchical Inheritance
When two or more classes inherits a class Cat extends Animal{
single class, it is known as void meow()
hierarchical inheritance. In the {System.out.println("meowing...");}
example given below, Dog and Cat }
classes inherits the Animal class, so
there is hierarchical inheritance. class Test{
class Animal{ public static void main(String args[])
{
void eat()
{System.out.println("eating...");} Cat c=new Cat();
} c.meow();
class Dog extends Animal{ c.eat();
void bark() //c.bark(); //C.T.Error
{System.out.println("barking...");} }}
} OUTPUT:
meowing... eating...
3. Hierarchical Inheritance
class Bird {
Parrot par = new Parrot();
void fly() {
Crow cro = new Crow();
System.out.println("I am a Bird");
//Call methods of Parrot Class
}}
par.whatColourAmI();
class Parrot extends Bird {
par.fly();
void whatColourAmI() {
//Call methods of Crow Class
System.out.println("I am green!");
cro.whatColourAmI();
}}
cro.fly();
class Crow extends Bird {
}}
void whatColourAmI() {
OUTPUT:
System.out.println("I am black!"); I am green!
}} I am a Bird
class Test { I am black!
I am a Bird
public static void main(String args[]) {
Why multiple inheritance is not
supported in java?
To reduce the complexity and class A{
simplify the language, multiple void msg()
inheritance is not supported in java. {System.out.println("Hello");} }
Consider a scenario where A, B, and class B{
C are three classes. The C class
inherits A and B classes. If A and B void msg()
classes have the same method and {System.out.println("Welcome");} }
you call it from child class object, class C extends A,B{
there will be ambiguity to call the
method of A or B class. public static void main(String arg
s[]){
Since compile-time errors are better
than runtime errors, Java renders C obj=new C();
compile-time error if you inherit 2 obj.msg();//
classes. So whether you have same Now which msg() method would be in
method or different, there will be voked?
compile time error.
} }
OUTPUT:
Why multiple inheritance is not
supported in java?
To reduce the complexity and class A{
simplify the language, multiple void msg()
inheritance is not supported in java. {System.out.println("Hello");} }
Consider a scenario where A, B, and class B{
C are three classes. The C class
inherits A and B classes. If A and B void msg()
classes have the same method and {System.out.println("Welcome");} }
you call it from child class object, class C extends A,B{
there will be ambiguity to call the
method of A or B class. public static void main(String arg
s[]){
Since compile-time errors are better
than runtime errors, Java renders C obj=new C();
compile-time error if you inherit 2 obj.msg();//
classes. So whether you have same Now which msg() method would be in
method or different, there will be voked?
compile time error.
} }
OUTPUT:
Method Overriding
If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.
Usage of Java Method Overriding
• Method overriding is used to provide the specific implementation of a
method which is already provided by its superclass.
• Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
Understanding the problem without
method overriding
class Vehicle{ Output:
void run() Vehicle is running
{ System.out.println("Vehicle is
running");}
Problem is that if we have to provide
} a specific implementation of run()
//Creating a child class method in subclass that is why we
use method overriding.
class Bike extends Vehicle{
public static void main(String args[])
{
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class
instance
obj.run();
Example:
class Vehicle{ public static void main(String args[]){
void run(){
System.out.println("Vehicle is Bike obj = new Bike(); //creating
running"); object
}} obj.run(); //calling method
//Creating a child class } }
class Bike extends Vehicle{
//defining the same method as in Output:
the parent class Bike is running safely
void run(){
System.out.println("Bike is running
safely");
}
A real example of Java Method
Overriding
Consider a scenario where Bank is a class that provides functionality to get
the rate of interest. However, the rate of interest varies according to banks.
For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate
of interest.
Example:
SBI s=new SBI();
class Bank{
ICICI i=new ICICI();
int getRateOfInterest(){return 0;} }
AXIS a=new AXIS();
//Creating child classes.
System.out.println("SBI Rate of
class SBI extends Bank{ Interest: "+s.getRateOfInterest());
int getRateOfInterest(){return 8;} } System.out.println("ICICI Rate of
class ICICI extends Bank{ Interest: "+i.getRateOfInterest());
int getRateOfInterest(){return 7;} } System.out.println("AXIS Rate of
Interest: "+a.getRateOfInterest());
Class AXIS extends Bank{
}}
int getRateOfInterest(){return 9;}
Output:
}
SBI Rate of Interest: 8
class Test{ ICICI Rate of Interest: 7
public static void main(String args[]){ AXIS Rate of Interest: 9
SUPER KEYWORD:
• The super keyword in Java is a reference variable which is used to refer
immediate parent class object.

• Whenever you create the instance of subclass, an instance of parent


class is created implicitly which is referred by super reference variable.

Usage of Java super Keyword


• super can be used to refer immediate parent class instance variable.
• super can be used to invoke immediate parent class method.
• super() can be used to invoke immediate parent class constructor.
USAGE OF SUPER KEYWORD:
1) super is used to refer immediate
parent class instance variable.
We can use super keyword to access the class Test {
data member or field of parent class. It
public static void main(String args[]){
is used if parent class and child class
have same fields. Example: Dog d=new Dog();
class Animal{ d.printColor();
String color="white"; }}
} OUTPUT:
class Dog extends Animal{ brown
String color="brown"; white
void printColor(){ In the above example, Animal and Dog
both classes have a common property
System.out.println(color);//prints color of
color. If we print color property, it will
Dog class
print the color of current class by
System.out.println(super.color);//prints default. To access the parent property,
color of Animal class we need to use super keyword.
} }
2) super can be used to invoke
parent class method } }
The super keyword can also be used to class Test{
invoke parent class method. It should be
used if subclass contains the same public static void main(String args[]){
method as parent class. In other words, Dog d=new Dog();
it is used if method is overridden.
Example: d.work();

class Animal{ }}

void eat() OUTPUT:


{System.out.println("eating...");} eating bread...
} eating...
class Dog extends Animal{ barking...
void eat(){System.out.println("eating In the above example Animal and Dog
bread...");} both classes have eat() method if we
void bark() call eat() method from Dog class, it will
{System.out.println("barking...");} call the eat() method of Dog class by
default because priority is given to
void work(){ local. To call the parent class method,
eat(); we need to use super keyword.
3) super is used to invoke parent
class constructor class Test{
The super keyword can also be used to public static void main(String args[]){
invoke the parent class constructor. Let's
see a simple example: Dog d=new Dog();

class Animal{ }}

Animal(){System.out.println("animal is OUTPUT:
created");} animal is created
} dog is created
class Dog extends Animal{ Note: super() is added in each class
Dog(){ constructor automatically by compiler
if there is no super() or this().
super();
System.out.println("dog is created");
}
}
Example of super keyword where super() is provided
by the compiler implicitly.
OUTPUT:
Another example of super keyword animal is created
where super() is provided by the
compiler implicitly. dog is created

class Animal{ Note: super() is added in each class


constructor automatically by compiler
Animal(){System.out.println("animal is if there is no super() or this(). As we
created");} know well that default constructor is
} provided by compiler automatically if
there is no constructor. But, it also adds
class Dog extends Animal{ super() as the first statement.
Dog(){
System.out.println("dog is created");
}
}
class Test{
public static void main(String args[]){
Dog d=new Dog();
Example of super keyword where super() is provided by the
compiler implicitly.
Instanceof operator

• The java instanceof operator is used to test


whether the object is an instance of the specified type
(class or subclass or interface).
• The instanceof in java is also known as
type comparison operator because it compares the
instance with type. It returns either true or false. If we
apply the instanceof operator with any variable that
has null value, it returns false.
• Its syntax is
objectName instanceOf className;
• Here, if objectName is an instance of className, the
operator returns true. Otherwise, it returns false.
Instanceof operator

class Test{
public static void main(String args[]){
Test s=new Test();
System.out.println(s instanceof Test);//true
}
}
OUTPUT:
true
Instanceof operator
class Test {
public static void main(String[] args) {
// create a variable of string type
String name = “BCA CLASS";
// checks if name is instance of String
boolean result1 = name instanceof String;
System.out.println("name is an instance of String: " + result1);
// create an object of Test class
Test obj = new Test();
// checks if obj is an instance of Test
boolean result2 = obj instanceof Test;
System.out.println("obj is an instance of Test: " + result2);
}}
OUTPUT:
name is an instance of String: true
obj is an instance of Test: true
Instanceof operator

class Animal{}
class Dog1 extends Animal{//Dog inherits Animal
public static void main(String args[]){
Dog1 d=new Dog1();
System.out.println(d instanceof Animal);//true
} }
OUTPUT:
true
An object of subclass type is also a type of parent class. For
example, if Dog extends Animal then object of Dog can be referred
by either Dog or Animal class.
instanceof in java with a variable that have null value

If we apply instanceof operator with a variable that have null


value, it returns false. Let's see the example given below where we
apply instanceof operator with the variable that have null value.

class Dog{
public static void main(String args[]){
Dog d=null;
System.out.println(d instanceof Dog);//false
}
}
OUTPUT:
false

You might also like