0% found this document useful (0 votes)
40 views59 pages

Inheritance in Java

Inheritance in Java allows one class to acquire properties and behaviors of another class. Method overriding provides specific implementation of a method defined in a parent class. Rules for overriding include the method name and parameters matching the parent class and an inheritance relationship between classes. This allows for runtime polymorphism where the specific implementation of a method is determined based on the object type. Examples demonstrate overriding the run method to specify behavior for a Bike class versus the parent Vehicle class.

Uploaded by

singharushi948
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
40 views59 pages

Inheritance in Java

Inheritance in Java allows one class to acquire properties and behaviors of another class. Method overriding provides specific implementation of a method defined in a parent class. Rules for overriding include the method name and parameters matching the parent class and an inheritance relationship between classes. This allows for runtime polymorphism where the specific implementation of a method is determined based on the object type. Examples demonstrate overriding the run method to specify behavior for a Bike class versus the parent Vehicle class.

Uploaded by

singharushi948
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 59

Inheritance in Java

Inheritance in java is a mechanism in which one


object acquires all the properties and behaviors of
parent object.
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 parent class, and you can add
new methods and fields also.
Inheritance represents the IS-A relationship, also
known as parent-child relationship.
Why use inheritance in java
 For Method Overriding (so runtime polymorphism

can be achieved).
 For Code Reusability.

Syntax of Java Inheritance

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }
The extends keyword indicates that you are making
a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is
called a super class. The new class is called a
subclass.

Understanding the simple example of inheritance

As displayed in the above figure, Programmer is the


subclass and Employee is the superclass. Relationship
between two classes is Programmer IS-A
Employee. It means that Programmer is a type of
Employee.
1. class Employee
2. {
3. float salary=40000;
4. }
5. class Programmer extends Employee {
6. int bonus=10000;
7. public static void main(String args[]){
8. Programmer p=new Programmer ();
9. System.out.println("Programmer salary is:"+p.salar
y);
10. System.out.println("Bonus of Programmer is:"+p.
bonus);
11. }
12. }
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access
the field of own class as well as of Employee class i.e.
code reusability.

Types of inheritance in java


On the basis of class, there can be three types of
inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance
is supported through interface only. We will learn
about interfaces later.
Note: Multiple inheritance is not supported in
java through class.

When a class extends multiple classes i.e. known as


multiple inheritance. For Example:
Q) Why multiple inheritance is not supported in java?
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 same method and you call it from child
class object, there will be ambiguity to call method of
A or B class.
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 now.
Class A extend B
{
Msg();
Msg();}
A 0 = new A()
o.msg()
super.msg()
A ->B,C
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be i
nvoked?
12. }
13. }
Test it Now
Compile Time Error
Next TopicAggregation in java (HAS-A)

C o = new c()
0.msg();
Super.msg();

Aggregation in Java
If a class have an entity reference, it is known as
Aggregation. Aggregation represents HAS-A relationship.
Consider a situation, Employee object contains many
informations such as id, name, emailId etc. It contains
one more object named address, which contains its own
informations such as city, state, country, zipcode etc. as
given below.
1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
6. }
In such case, Employee has an entity reference address,
so relationship is Employee HAS-A address.
Why use Aggregation?
 For Code Reusability.

Simple Example of Aggregation

In this example, we have created the reference of


Operation class in the Circle class.
1. class Operation{
2. int square(int n)
3. {
4. return n*n;
5. }
6. }
7.
8. class Circle{
9. Operation op;//aggregation
10. double pi=3.14;
11.
12. double area(int radius){
13. op=new Operation();
14. int rsquare=op.square(radius);//code reusability (
i.e. delegates the method call).
15. return pi*rsquare;
16. }
17.
18.
19.
20. public static void main(String args[]){
21. Circle c=new Circle();
22. double result=c.area(5);
23. System.out.println(result);
24. }
25. }
Test it Now
Output:78.5

When use Aggregation?


 Code reuse is also best achieved by aggregation

when there is no is-a relationship.


 Inheritance should be used only if the relationship is-

a is maintained throughout the lifetime of the objects


involved; otherwise, aggregation is the best choice.
Understanding meaningful example of Aggregation

In this example, Employee has an object of Address,


address object contains its own informations such as city,
state, country etc. In such case relationship is Employee
HAS-A address.
Address.java
1. public class Address {
2. String city,state,country;
3.
4. public Address(String city, String state, String country) {

5. this.city = city;
6. this.state = state;
7. this.country = country;
8. }
9.
10. }
Emp.java
1. public class Emp {
2. int id;
3. String name;
4. Address address;
5.
6. public Emp(int id, String name,Address address) {
7. this.id = id;
8. this.name = name;
9. this.address=address;
10. }
11.
12. void display(){
13. System.out.println(id+" "+name);
14. System.out.println(address.city+" "+address.state+
" "+address.country);
15. }
16.
17. public static void main(String[] args) {
18. Address address1=new Address("gzb","UP","india")
;
19. Address address2=new Address("gno","UP","india")
;
20.
21. Emp e=new Emp(111,"varun",address1);
22. Emp e2=new Emp(112,"arun",address2);
23.
24. e.display();
25. e2.display();
26.
27. }
28. }
Test it Now
Output:111 varun
gzb UP india
112 arun
gno UP india
Method Overriding in Java

If subclass (child class) has the same method as declared


in the parent class, it is known as method overriding
in java.
In other words, If subclass provides the specific
implementation of the method that has been provided by
one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide specific
implementation of a method that is already
provided by its super class.
o Method overriding is used for runtime
polymorphism
Rules for Java Method Overriding

1. method must have same name as in the parent


class
2. method must have same parameter as in the parent
class.
3. must be IS-A relationship (inheritance).

Understanding the problem without method


overriding
Let's understand the problem that we may face in the
program if we don't use method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5.
6. public static void main(String args[]){
7. Bike obj = new Bike();
8. obj.run();
9. }
10. }
Test it Now
Output: Vehicle is running
Problem is that I have to provide a specific
implementation of run() method in subclass that is why
we use method overriding.

Example of method overriding

In this example, we have defined the run method in the


subclass as defined in the parent class but it has some
specific implementation. The name and parameter of the
method is same and there is IS-A relationship between
the classes, so there is method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run()
6. {
7. System.out.println("Bike is running safely");
8. }
9.
10. public static void main(String args[]){
11. Bike2 obj = new Bike2();
12. obj.run();
13. }
Test it Now
Output: Bike is running safely
Real 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.

1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }
8.
9. class ICICI extends Bank
10. {
11. int getRateOfInterest(){return 7;}
12. }
13. class AXIS extends Bank
14. {
15. int getRateOfInterest()
16. {
17. return 9;}
18. }
19.
20. class Test2{
21. public static void main(String args[]){
22. SBI s=new SBI();
23. ICICI i=new ICICI();
24. AXIS a=new AXIS();
25. System.out.println("SBI Rate of Interest: "+s.getRat
eOfInterest());
26. System.out.println("ICICI Rate of Interest: "+i.getR
ateOfInterest());
27. System.out.println("AXIS Rate of Interest: "+a.getR
ateOfInterest());
28. }
29. }
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Can we override static method?
No, static method cannot be overridden. It can be
proved by runtime polymorphism, so we.
Why we cannot override static method?
because static method is bound with class whereas
instance method is bound with object. Static belongs to
class area and instance belongs to heap area.

Can we override java main method?


No, because main is a static method.

Difference between method Overloading and Method


Overriding in java

Covariant Return Type


The covariant return type specifies that the return
type may vary in the same direction as the subclass.
Before Java5, it was not possible to override any
method by changing the return type. But now, since
Java5, it is possible to override method by changing
the return type if subclass overrides any method
whose return type is Non-Primitive but it changes its
return type to subclass type. Let's take a simple
example:
Note: If you are beginner to java, skip this
topic and return to it after OOPs concepts.

Simple example of Covariant Return Type


1. class A{
2. A get(){return this;}
3. }
4.
5. class B1 extends A{
6. B1 get(){return this;}
7. void message(){System.out.println("welcome to covar
iant return type");}
8.
9. public static void main(String args[]){
10. new B1().get().message();
11. }
12. }
Test it Now
Output:welcome to covariant return type
As you can see in the above example, the return type
of the get() method of A class is A but the return type
of the get() method of B class is B. Both methods
have different return type but it is method overriding.
This is known as covariant return type.

super keyword in java


The super keyword in java is a reference variable
that is used to refer immediate parent class object.

Whenever you create the instance of subclass,


an instance of parent class is created
implicitly i.e. referred by super reference
variable.
Usage of java super Keyword
1. super is used to refer immediate parent class
instance variable.
2. super() is used to invoke immediate parent class
constructor.
3. super is used to invoke immediate parent class
method.
1) super is used to refer immediate parent class
instance variable.
Problem without super keyword
1. class Vehicle{
2. int speed=50;
3. }
4. class Bike3 extends Vehicle{
5. int speed=100;
6. void display(){
7. System.out.println(speed);//will print speed of Bike

8. }
9. public static void main(String args[]){
10. Bike3 b=new Bike3();
11. b.display();
12. }
13. }
Test it Now
Output:100
In the above example Vehicle and Bike both class
have a common property speed. Instance variable
of current class is refered by instance bydefault,
but I have to refer parent class instance variable
that is why we use super keyword to distinguish
between parent class instance variable and current
class instance variable.

Solution by super keyword


1. //example of super keyword
2.
3. class Vehicle{
4. int speed=50;
5. }
6.
7. class Bike4 extends Vehicle{
8. int speed=100;
9.
10. void display(){
11. System.out.println(super.speed);//will print spee
d of Vehicle now
12. }
13. public static void main(String args[]){
14. Bike4 b=new Bike4();
15. b.display();
16.
17. }
18. }
Test it Now
Output:50
2) super is used to invoke parent class
constructor.
The super keyword can also be used to invoke the
parent class constructor as given below:
1. class Vehicle{
2. Vehicle(){System.out.println("Vehicle is created");}
3. }
4.
5. class Bike5 extends Vehicle{
6. Bike5(){
7. super();//will invoke parent class constructor
8. System.out.println("Bike is created");
9. }
10. public static void main(String args[]){
11. Bike5 b=new Bike5();
12.
13. }
14. }
Test it Now
Output:Vehicle is created
Bike is created
Note: super() is added in each class constructor
automatically by compiler.

As we know well that default constructor is provided


by compiler automatically but it also adds super() for
the first statement.If you are creating your own
constructor and you don't have either this() or super()
as the first statement, compiler will provide super() as
the first statement of the constructor.
Another example of super keyword where
super() is provided by the compiler implicitly.
1.
2.
3. class Vehicle{
4. Vehicle(){System.out.println("Vehicle is created");}
5. }
6.
7. class Bike6 extends Vehicle{
8. int speed;
9. Bike6(int speed){
10. this.speed=speed;
11. System.out.println(speed);
12. }
13. public static void main(String args[]){
14. Bike6 b=new Bike6(10);
15. }
16. }
Test it Now
Output:Vehicle is created
10
3) super can be used to invoke parent class method
The super keyword can also be used to invoke
parent class method. It should be used in case
subclass contains the same method as parent class
as in the example given below:
1. class Person{
2. void message(){System.out.println("welcome");}
3. }
4.
5. class Student16 extends Person{
6. void message(){System.out.println("welcome to java"
);}
7.
8. void display(){
9. message();//will invoke current class message() meth
od
10. super.message();//will invoke parent class messag
e() method
11. }
12.
13. public static void main(String args[]){
14. Student16 s=new Student16();
15. s.display();
16. }
17. }
Test it Now
Output:welcome to java
welcome
In the above example Student and Person both
classes have message() method if we call
message() method from Student class, it will call
the message() method of Student class not of
Person class because priority is given to local.

In case there is no method in subclass as parent,


there is no need to use super. In the example
given below message () method is invoked from
Student class but Student class does not have
message() method, so you can directly call
message () method.

Program in case super is not required


1. class Person{
2. void message(){System.out.println("welcome");}
3. }
4.
5. class Student17 extends Person{
6.
7. void display(){
8. message();//will invoke parent class message() metho
d
9. }
10.
11. public static void main(String args[]){
12. Student17 s=new Student17();
13. s.display();
14. }
15. }
Test it Now
Output:welcome

Instance Initializer block is used to initialize the


instance data member. It run each time when
object of the class is created.
The initialization of the instance variable can be
directly but there can be performed extra
operations while initializing the instance variable in
the instance initializer block.

Que) What is the use of instance initializer


block while we can directly assign a value in
instance data member? For example:
1. class Bike{
2. int speed=100;
3. }
Why use instance initializer block?
Suppose I have to perform some operations while
assigning value to instance data member e.g. a for
loop to fill a complex array or error handling etc.

Example of instance initializer block


Let's see the simple example of instance initializer
block the performs initialization.
1. class Bike7{
2. int speed;
3.
4. Bike7(){System.out.println("speed is "+speed);}
5.
6. {speed=100;}
7.
8. public static void main(String args[]){
9. Bike7 b1=new Bike7();
10. Bike7 b2=new Bike7();
11. }
12. }
Test it Now
Output:speed is 100
speed is 100

There are three places in java where you can


perform operations:
1. method
2. constructor
3. block

What is invoked firstly instance initializer block or


constructor?
1. class Bike8{
2. int speed;
3.
4. Bike8(){System.out.println("constructor is invoked"
);}
5.
6. {System.out.println("instance initializer block invok
ed");}
7.
8. public static void main(String args[]){
9. Bike8 b1=new Bike8();
10. Bike8 b2=new Bike8();
11. }
12. }
Test it Now
Output:instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked
In the above example, it seems that instance
initializer block is firstly invoked but NO. Instance
intializer block is invoked at the time of object
creation. The java compiler copies the instance
initializer block in the constructor after the first
statement super(). So firstly, constructor is
invoked. Let's understand it by the figure given
below:

Note: The java compiler copies the code of


instance initializer block in every constructor.

Rules for instance initializer block :


There are mainly three rules for the instance
initializer block. They are as follows:

1. The instance initializer block is created when


instance of the class is created.
2. The instance initializer block is invoked after the
parent class constructor is invoked (i.e. after
super() constructor call).
3. The instance initializer block comes in the order
in which they appear.
Program of instance initializer block that is invoked
after super()
1. class A{
2. A(){
3. System.out.println("parent class constructor invoked")
;
4. }
5. }
6. class B2 extends A{
7. B2(){
8. super();
9. System.out.println("child class constructor invoked");

10. }
11.
12. {System.out.println("instance initializer block is inv
oked");}
13.
14. public static void main(String args[]){
15. B2 b=new B2();
16. }
17. }
Test it Now
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked

Another example of instance block


1. class A{
2. A(){
3. System.out.println("parent class constructor invoked")
;
4. }
5. }
6.
7. class B3 extends A{
8. B3(){
9. super();
10. System.out.println("child class constructor invoked"
);
11. }
12.
13. B3(int a){
14. super();
15. System.out.println("child class constructor invoked
"+a);
16. }
17.
18. {System.out.println("instance initializer block is inv
oked");}
19.
20. public static void main(String args[]){
21. B3 b1=new B3();
22. B3 b2=new B3(10);
23. }
24. }
Test it Now
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
parent class constructor invoked
instance initializer block is invoked
child class constructor invoked 10
Next TopicFinal Keyword

<<prevnext>>

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:
1. variable
2. method
3. 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.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
Output:Compile Time Error

2) Java final method


If you make any method as final, you cannot override
it.
Example of final method
1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 1
00kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Test it Now
Output:Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.
Example of final class
1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 1
00kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda();
8. honda.run();
9. }
10. }
Test it Now
Output:Compile Time Error

Q) Is final method inherited?


Ans) Yes, final method is inherited but you cannot
override it. For Example:
1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
Test it Now
Output:running...
Q) What is blank or uninitialized final variable?
A final variable that is not initialized at the time of
declaration is known as blank final variable.
If you want to create a variable that is initialized at
the time of creating object and once initialized may
not be changed, it is useful. For example PAN CARD
number of an employee.
It can be initialized only in constructor.
Example of blank final variable
1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
Que) Can we initialize blank final variable?
Yes, but only in constructor. For example:
1. class Bike10{
2. final int speedlimit;//blank final variable
3.
4. Bike10(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike10();
11. }
12. }
Test it Now
Output:70

static blank final variable


A static final variable that is not initialized at the time
of declaration is known as static blank final variable.
It can be initialized only in static block.
Example of static blank final variable
1. class A{
2. static final int data;//static blank final variable
3. static{ data=50;}
4. public static void main(String args[]){
5. System.out.println(A.data);
6. }
7. }

Q) What is final parameter?


If you declare any parameter as final, you cannot
change the value of it.
1. class Bike11{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike11 b=new Bike11();
8. b.cube(5);
9. }
10. }
Test it Now
Output:Compile Time Error

Q) Can we declare a constructor final?


No, because constructor is never inherited.
Next TopicRuntime Polymorphism in java

← prevnext →

Polymorphism in Java
Polymorphism in java is a concept by which we
can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly
and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means
many forms.
There are two types of polymorphism in java: compile
time polymorphism and runtime polymorphism. We
can perform polymorphism in java by method
overloading and method overriding.
If you overload static method in java, it is the
example of compile time polymorphism. Here, we will
focus on runtime polymorphism in java.

Runtime Polymorphism in Java


Runtime polymorphism or Dynamic Method
Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than
compile-time.
In this process, an overridden method is called
through the reference variable of a superclass. The
determination of the method to be called is based on
the object being referred to by the reference variable.
Let's first understand the upcasting before Runtime
Polymorphism.
Upcasting
When reference variable of Parent class refers to the
object of Child class, it is known as upcasting. For
example:

1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting

Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and


Splendar. Splendar class extends Bike class and
overrides its run() method. We are calling the run
method by the reference variable of Parent class. Since
it refers to the subclass object and subclass method
overrides the Parent class method, subclass method is
invoked at runtime.
Since method invocation is determined by the JVM
not compiler, it is known as runtime polymorphism.
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splender extends Bike{
5. void run(){System.out.println("running safely with 6
0km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splender();//upcasting
9. b.run();
10. }
11. }
Test it Now
Output:running safely with 60km.
Real example of Java Runtime Polymorphism
Consider a scenario, Bank is a class that provides
method to get the rate of interest. But, rate of
interest may differ according to banks. For example,
SBI, ICICI and AXIS banks could provide 8%, 7% and
9% rate of interest.

Note: It is also given in method overriding but there


was no upcasting.
1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }
8.
9. class ICICI extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12. class AXIS extends Bank{
13. int getRateOfInterest(){return 9;}
14. }
15.
16. class Test3{
17. public static void main(String args[]){
18. Bank b1=new SBI();
19. Bank b2=new ICICI();
20. Bank b3=new AXIS();
21. System.out.println("SBI Rate of Interest: "+b1.get
RateOfInterest());
22. System.out.println("ICICI Rate of Interest: "+b2.ge
tRateOfInterest());
23. System.out.println("AXIS Rate of Interest: "+b3.ge
tRateOfInterest());
24. }
25. }
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Java Runtime Polymorphism with data member


Method is overridden not the datamembers, so
runtime polymorphism can't be achieved by data
members.
In the example given below, both the classes have
a datamember speedlimit, we are accessing the
datamember by the reference variable of Parent
class which refers to the subclass object. Since we
are accessing the datamember which is not
overridden, hence it will access the datamember of
Parent class always.

Rule: Runtime polymorphism can't be achieved


by data members.
1. class Bike{
2. int speedlimit=90;
3. }
4. class Honda3 extends Bike{
5. int speedlimit=150;
6.
7. public static void main(String args[]){
8. Bike obj=new Honda3();
9. System.out.println(obj.speedlimit);//90
10. }
Test it Now
Output:90
Java Runtime Polymorphism with Multilevel
Inheritance
Let's see the simple example of Runtime
Polymorphism with multilevel inheritance.
1. class Animal{
2. void eat(){System.out.println("eating");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("eating fruits");}
7. }
8.
9. class BabyDog extends Dog{
10. void eat(){System.out.println("drinking milk");}
11.
12. public static void main(String args[]){
13. Animal a1,a2,a3;
14. a1=new Animal();
15. a2=new Dog();
16. a3=new BabyDog();
17.
18. a1.eat();
19. a2.eat();
20. a3.eat();
21. }
22. }
Test it Now
Output: eating
eating fruits
drinking Milk

Try for Output


1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7. }
8.
9. class BabyDog1 extends Dog{
10. public static void main(String args[]){
11. Animal a=new BabyDog1();
12. a.eat();
13. }}
Test it Now
Output: Dog is eating
Since, BabyDog is not overriding the eat() method, so
eat() method of Dog class is invoked.

Static Binding and Dynamic Binding

Connecting a method call to the method body is


known as binding.
There are two types of binding
1. static binding (also known as early binding).
2. dynamic binding (also known as late binding).
Understanding Type
Let's understand the type of instance.
1) variables have a type
Each variable has a type, it may be primitive and non-
primitive.
1. int data=30;
Here data variable is a type of int.
2) References have a type
1. class Dog
2. {
3. public static void main(String args[])
4. {
5. Dog d1;//Here d1 is a type of Dog
6. }
7. }
3) Objects have a type
An object is an instance of particular java class,but
it is also an instance of its superclass.
1. class Animal{}
2.
3. class Dog extends Animal{
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. }
7. }
Here d1 is an instance of Dog class, but it is also an
instance of Animal.

static binding
When type of the object is determined at compiled
time(by the compiler), it is known as static binding.
If there is any private, final or static method in a
class, there is static binding.
Example of static binding
1. class Dog{
2. private void eat(){System.out.println("dog is eating...
");}
3.
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. d1.eat();
7. }
8. }

Dynamic binding
When type of the object is determined at run-time, it
is known as dynamic binding.
Example of dynamic binding
1. class Animal{
2. void eat(){System.out.println("animal is eating...");}

3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7.
8. public static void main(String args[]){
9. Animal a=new Dog();
10. a.eat();
11. }
12. }
Test it Now
Output:dog is eating...
In the above example object type cannot be
determined by the compiler, because the instance
of Dog is also an instance of Animal.So compiler
doesn't know its type, only its base type.
Next TopicDowncasting and instanceof operator

<<prevnext>>

Java instanceof
1. java instanceof
2. Example of instanceof operator
3. Applying the instanceof operator with a variable
the have null value
4. Downcasting with instanceof operator
5. Downcasting without 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 operatorbecause 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.
Simple example of java instanceof

Let's see the simple example of instance operator


where it tests the current class.
1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple);//true
5. }
6. }
Test it Now
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.
Another example of java instanceof operator
1. class Animal{}
2. class Dog1 extends Animal{//Dog inherits Animal
3.
4. public static void main(String args[]){
5. Dog1 d=new Dog1();
6. System.out.println(d instanceof Animal);//true
7. }
8. }
Test it Now
Output:true

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.
1. class Dog2{
2. public static void main(String args[]){
3. Dog2 d=null;
4. System.out.println(d instanceof Dog2);//false
5. }
6. }
Test it Now
Output:false

Downcasting with java instanceof operator


When Subclass type refers to the object of Parent
class, it is known as downcasting. If we perform it
directly, compiler gives Compilation error. If you
perform it by typecasting, ClassCastException is
thrown at runtime. But if we use instanceof operator,
downcasting is possible.
1. Dog d=new Animal();//Compilation error
If we perform downcasting by typecasting,
ClassCastException is thrown at runtime.
1. Dog d=(Dog)new Animal();
2. //Compiles successfully but ClassCastException is thro
wn at runtime
Possibility of downcasting with instanceof
Let's see the example, where downcasting is possible
by instanceof operator.
1. class Animal { }
2.
3. class Dog3 extends Animal {
4. static void method(Animal a) {
5. if(a instanceof Dog3){
6. Dog3 d=(Dog3)a;//downcasting
7. System.out.println("ok downcasting performed");

8. }
9. }
10.
11. public static void main (String [] args) {
12. Animal a=new Dog3();
13. Dog3.method(a);
14. }
15.
16. }
Test it Now
Output:ok downcasting performed
Downcasting without the use of java instanceof
Downcasting can also be performed without the use
of instanceof operator as displayed in the following
example:
1. class Animal { }
2. class Dog4 extends Animal {
3. static void method(Animal a) {
4. Dog4 d=(Dog4)a;//downcasting
5. System.out.println("ok downcasting performed");

6. }
7. public static void main (String [] args) {
8. Animal a=new Dog4();
9. Dog4.method(a);
10. }
11. }
Test it Now
Output:ok downcasting performed
Let's take closer look at this, actual object that is
referred by a, is an object of Dog class. So if we
downcast it, it is fine. But what will happen if we
write:
1. Animal a=new Animal();
2. Dog.method(a);
3. //Now ClassCastException but not in case of instanceo
f operator
Understanding Real use of instanceof in java
Let's see the real use of instanceof keyword by the
example given below.
1. interface Printable{}
2. class A implements Printable{
3. public void a(){System.out.println("a method");}
4. }
5. class B implements Printable{
6. public void b(){System.out.println("b method");}
7. }
8.
9. class Call{
10. void invoke(Printable p){//upcasting
11. if(p instanceof A){
12. A a=(A)p;//Downcasting
13. a.a();
14. }
15. if(p instanceof B){
16. B b=(B)p;//Downcasting
17. b.b();
18. }
19.
20. }
21. }//end of Call class
22.
23. class Test4{
24. public static void main(String args[]){
25. Printable p=new B();
26. Call c=new Call();
27. c.invoke(p);
28. }
29. }
Test it Now
Output: b method
Next TopicAbstract class in java

<<prevnext>>

Abstract class in Java


A class that is declared with abstract keyword, is
known as abstract class in java. It can have abstract
and non-abstract methods (method with body).
Before learning java abstract class, let's understand
the abstraction in java first.

Abstraction in Java
Abstraction is a process of hiding the
implementation details and showing only functionality
to the user.
Another way, it shows only important things to the
user and hides the internal details for example
sending sms, you just 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 Abstaction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)

Abstract class in Java


A class that is declared as abstract is known
as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
Example abstract class
1. abstract class A{}

abstract method
A method that is declared as abstract and does not
have implementation is known as abstract method.

Example abstract method


1. abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method

In this example, Bike the abstract class that contains


only one abstract method run. It implementation is
provided by the Honda class.
1. abstract class Bike{
2. abstract void run();
3. }
4.
5. class Honda4 extends Bike{
6. void run(){System.out.println("running safely..");}
7.
8. public static void main(String args[]){
9. Bike obj = new Honda4();
10. obj.run();
11. }
12. }
Test it Now
running safely..

Understanding the real scenario of abstract class


In this example, Shape is the abstract class, its
implementation is provided by the Rectangle and
Circle classes. Mostly, we don't know about the
implementation class (i.e. hidden to the end user)
and object of the implementation class is provided by
the factory method.
A factory method is the method that returns the
instance of the class. We will learn about the factory
method later.
In this example, if you create the instance of
Rectangle class, draw() method of Rectangle class will
be invoked.
File: TestAbstraction1.java
1. abstract class Shape{
2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by othe
rs i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw()
7. {
8. System.out.println("drawing rectangle");}
9. }
10.
11. class Circle1 extends Shape{
12. void draw(){System.out.println("drawing circle");}
13. }
14.
15. //In real scenario, method is called by programmer
or user
16. class TestAbstraction1{
17. public static void main(String args[]){
18. Shape s=new Circle1();//In real scenario, object is
provided through method e.g. getShape() method
19. s.draw();
20. }
21. }
Test it Now
drawing circle
Another example of abstract class in java
File: TestBank.java
1. abstract class Bank{
2. abstract int getRateOfInterest();
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 7;}
7. }
8. class PNB extends Bank{
9. int getRateOfInterest(){return 7;}
10. }
11.
12. class TestBank{
13. public static void main(String args[]){
14. Bank b=new SBI();//if object is PNB, method of PN
B will be invoked
15. int interest=b.getRateOfInterest();
16. System.out.println("Rate of Interest is: "+interest+
" %");
17. }}
Test it Now
Rate of Interest is: 7 %

Abstract class having constructor, data member,


methods etc.
An abstract class can have data member, abstract
method, method body, constructor and even main()
method.
File: TestAbstraction2.java
1. //example of abstract class that have method body
2. abstract class Bike{
3. Bike(){System.out.println("bike is created");}
4. abstract void run();
5. void changeGear(){System.out.println("gear change
d");}
6. }
7.
8. class Honda extends Bike{
9. void run(){System.out.println("running safely..");}
10. }
11. class TestAbstraction2{
12. public static void main(String args[]){
13. Bike obj = new Honda();
14. obj.run();
15. obj.changeGear();
16. }
17. }
Test it Now
bike is created
running safely..
gear changed
Rule: If there is any abstract method in a class,
that class must be abstract.
1. class Bike12{
2. abstract void run();
3. }
Test it Now
compile time error

Rule: If you are extending any abstract class


that have abstract method, you must either
provide the implementation of the method or
make this class abstract.

Another real scenario of abstract class


The abstract class can also be used to provide some
implementation of the interface. In such case, the
end user may not be forced to override all the
methods of the interface.
Note: If you are beginner to java, learn interface
first and skip this example.

1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A {
9. public void c(){System.out.println("I am C");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
Test it Now
Output: I am a
I am b
I am c
I am d

You might also like