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

Java 5 Polymorphism Overloading

Uploaded by

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

Java 5 Polymorphism Overloading

Uploaded by

amaleshmsc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Method Overloading:

* same method name different argument its called method overloading.

*its used in same class.

*its also called compile time polymorphism.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In Java, Method Overloading is not possible by changing the return type of


the method only.

1) Method Overloading: changing no. of


arguments
In this example, we have created two methods, first add() method
performs addition of two numbers and second add method
performs addition of three numbers.

In this example, we are creating static methods so that we don't


need to create instance for calling methods.

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
Test it Now
Output:
22
33

2) Method Overloading: changing data type of


arguments
In this example, we have created two methods that differs in data
type. The first add method receives two integer arguments and
second add method receives two double arguments.

1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b)
4. {
5. return a+b;
6. }
7. }
8. class TestOverloading2{
9. public static void main(String[] args){
10. System.out.println(Adder.add(11,11));
11. System.out.println(Adder.add(12.3,12.6));
12. }}
Output:
22
24.9

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.
Usage of Java Method Overriding

o Method overriding is used to provide the specific


implementation of a method which is already provided by its
superclass.
o Method overriding is used for runtime polymorphism
o Java method overriding is mostly used in Runtime Polymorphism
which we will learn in next pages.

Rules for Java Method Overriding

1. The method must have the same name as in the parent


class
2. The method must have the same parameter as in the parent
class.
3. There must be an IS-A relationship (inheritance).
4. /Java Program to illustrate the use of Java Method Overriding
5. //Creating a parent class.
6. class Vehicle{
7. //defining a method
8. void run(){System.out.println("Vehicle is running");}
9. }
10. //Creating a child class
11. class Bike2 extends Vehicle{
12. //defining the same method as in the parent class
13. void run(){System.out.println("Bike is running safely
");}

14. public static void main(String args[]){


15. Bike2 obj = new Bike2();//creating object
16. obj.run();//calling method
17. }
18. }

19. Bike is running safely


1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4. //Creating child classes.
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. //Test class to create objects and call the methods
16. class Test2{
17. public static void main(String args[]){
18. SBI s=new SBI();
19. ICICI i=new ICICI();
20. AXIS a=new AXIS();
21. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
22. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
23. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
24. }
25. }
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Why can we not override static method?


It is because the static method is bound with class whereas
instance method is bound with an object. Static belongs to the
class area, and an instance belongs to the heap area.
Main method overloading
1. public class MainMethodOverload3
2. {
3. //Overloaded main() method 1
4. public static void main(boolean args)
5. {
6. if (args)
7. {
8. System.out.println("First overloaded main() method executed");
9. System.out.println(args);
10. }
11. }
12. //Overloaded main method 2
13. public static void main(String str)
14. {
15. System.out.println("Second overloaded main() method executed");
16. System.out.println(str);
17. }
18. //Overloaded main method 3
19. public static void main(int args)
20. {
21. System.out.println("Third overloaded main() method executed");
22. System.out.println(args);
23. }
24. //Original main() method
25. public static void main(String[] args)
26. {
27. System.out.println("Original main() method executed");
28. System.out.println("Hello");
29. //invoking overloaded main() method 1
30. MainMethodOverload3.main(true);
31. //invoking overloaded main() method 2
32. MainMethodOverload3.main("mango");
33. //invoking overloaded main() method 3
34. MainMethodOverload3.main(112);
35. }
36. }

Output:

Original main() method executed


Hello
First overloaded main() method executed
true
Second overloaded main() method executed
mango
Third overloaded main() method executed
112

Mobile phone numbers are not stored as integers, as the integer data type
holds values that have the potential to be used in calculations. There is no
context for using a mobile phone number as part of a calculation, so it is
stored as a STRING value.

Super Keyword in Java


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

1. super can be used to refer immediate parent class instance


variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class
constructor.
1) super is used to refer immediate parent class
instance variable.
We can use super keyword to access the data member or field of parent
class. It is used if parent class and child class have same fields.

1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}

Output:
black
white

2) 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 if subclass contains the same method
as parent class. In other words, it is used if method is overridden.

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
Output
eating...
barking...

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class
constructor. Let's see a simple example:

1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}
Output:
animal is created
dog is created

Note: super() is added in each class constructor automatically by compiler


if there is no super() or this().

As we know well that default constructor is provided by compiler


automatically if there is no constructor. But, it also adds super()
as the first statement.

Another example of super keyword where super() is


provided by the compiler implicitly.

1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. System.out.println("dog is created");
7. }
8. }
9. class TestSuper4{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }}
Test it Now

Output:
animal is created
dog is created

super example: real use


Let's see the real use of super keyword. Here, Emp class inherits
Person class so all the properties of Person will be inherited to
Emp by default. To initialize all the property, we are using parent
class constructor from child class. In such way, we are reusing the
parent class constructor.

1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. this.id=id;
6. this.name=name;
7. }
8. }
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. this.salary=salary;
14. }
15. void display(){System.out.println(id+" "+name+"
"+salary);}
16. }
17. class TestSuper5{
18. public static void main(String[] args){
19. Emp e1=new Emp(1,"ankit",45000f);
20. e1.display();
21. }}
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.

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();
obj.run();
}
1. }//end of class
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. class Honda extends Bike{


5. void run(){System.out.println("running safely with 100kmph");}

6. public static void main(String args[]){


7. Honda honda= new Honda();
8. honda.run();
9. }
10. }
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 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }
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. }
Output:running...

Polymorphism in Java
Polymorphism in Java is a concept by which we can perform
a single action in 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 a static method in Java, it is the example of compile time


polymorphism. Here, we will focus on runtime polymorphism in java.

Upcasting
If the reference variable of Parent class refers to the object of
Child class, it is known as upcasting. For example:

Example of Java Runtime Polymorphism


we are creating two classes Bike and Splendor. Splendor 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, the subclass method is
invoked at runtime.

1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}

6. public static void main(String args[]){


7. Bike b = new Splendor();//upcasting
8. b.run();
9. }
10. }

Output:

running safely with 60km.

1. class Bank{
2. float getRateOfInterest(){return 0;}
3. }
4. class SBI extends Bank{
5. float getRateOfInterest(){return 8.4f;}
6. }
7. class ICICI extends Bank{
8. float getRateOfInterest(){return 7.3f;}
9. }
10. class AXIS extends Bank{
11. float getRateOfInterest(){return 9.7f;}
12. }
13. class TestPolymorphism{
14. public static void main(String args[]){
15. Bank b;
16. b=new SBI();
17. System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
18. b=new ICICI();
19. System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
20. b=new AXIS();
21. System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
22. }
23. }

Output:
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

Java Runtime Polymorphism Example: Animal


1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. }
7. class Cat extends Animal{
8. void eat(){System.out.println("eating rat...");}
9. }
10. class Lion extends Animal{
11. void eat(){System.out.println("eating meat...");}
12. }
13. class TestPolymorphism3{
14. public static void main(String[] args){
15. Animal a;
16. a=new Dog();
17. a.eat();
18. a=new Cat();
19. a.eat();
20. a=new Lion();
21. a.eat();
22. }}

Output:
eating bread...
eating rat...
eating meat...

Java Runtime Polymorphism with Data Member


A method is overridden, not the data members, so runtime
polymorphism can't be achieved by data members.

In the example given below, both the classes have a data


member speedlimit. We are accessing the data member by the
reference variable of Parent class which refers to the subclass
object. Since we are accessing the data member which is not
overridden, hence it will access the data member of the 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. }

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. class Dog extends Animal{
5. void eat(){System.out.println("eating fruits");}
6. }
7. class BabyDog extends Dog{
8. void eat(){System.out.println("drinking milk");}
9. public static void main(String args[]){
10. Animal a1,a2,a3;
11. a1=new Animal();
12. a2=new Dog();
13. a3=new BabyDog();
14. a1.eat();
15. a2.eat();
16. a3.eat();
17. }
18. }
1. Output:
eating
eating fruits
drinking Milk

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.History of Java

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. public static void main(String args[]){
3. Dog d1;//Here d1 is a type of Dog
4. }
5. }
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...

Instance initializer block


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 done 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 that
performs initialization.

2. class Bike7{
3. int speed;

4. Bike7(){System.out.println("speed is "+speed);}

5. {speed=100;}

6. public static void main(String args[]){


7. Bike7 b1=new Bike7();
8. Bike7 b2=new Bike7();
9. }
10. }
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 first, instance initializer block or


constructor?
1. class Bike8{
2. int speed;

3. Bike8(){System.out.println("constructor is invoked");}

4. {System.out.println("instance initializer block invoked");}

5. public static void main(String args[]){


6. Bike8 b1=new Bike8();
7. Bike8 b2=new Bike8();
8. }
9. }
Test it Now
Output:instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked

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()
11. class A{
12. A(){
13. System.out.println("parent class constructor invoked");
14. }
15. }
16. class B2 extends A{
17. B2(){
18. super();
19. System.out.println("child class constructor invoked");
20. }

21. {System.out.println("instance initializer block is invoked");}

22. public static void main(String args[]){


23. B2 b=new B2();
24. }
25. }
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. class B3 extends A{
7. B3(){
8. super();
9. System.out.println("child class constructor invoked");
10. }

11. B3(int a){


12. super();
13. System.out.println("child class constructor invoked "+a);
14. }

15. {System.out.println("instance initializer block is invoked");}

16. public static void main(String args[]){


17. B3 b1=new B3();
18. B3 b2=new B3(10);
19. }
20. }
Test it Now
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
Java instanceof
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.

Simple example of java instanceofJDK, JRE, and JVM


1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple1);//true
5. }
6. }
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. }
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. }
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 thrown 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. }
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. }
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 instanceof 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. class Call{
9. void invoke(Printable p){//upcasting
10. if(p instanceof A){
11. A a=(A)p;//Downcasting
12. a.a();
13. }
14. if(p instanceof B){
15. B b=(B)p;//Downcasting
16. b.b();
17. }
18. }
19. }//end of Call class

20. class Test4{


21. public static void main(String args[]){
22. Printable p=new B();
23. Call c=new Call();
24. c.invoke(p);
25. }
26. }
Test it Now
Output: b method

You might also like