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

Unit 2_Polymorphism

Uploaded by

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

Unit 2_Polymorphism

Uploaded by

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

Unit II

Polymorphism
➢ Polymorphism (from Greek, meaning “many forms”) is a feature that
allows one interface to be used for a general class of actions.

➢ Generally, polymorphism refers to the ability to appear in many forms.

➢ In Java it allows multiple objects of different subclasses to be treated as


objects of a single super class, while automatically selecting the proper
methods to apply to a particular object based on the subclass it belongs to.
➢ For example, given a base class shape, polymorphism enables the
programmer to define different area methods for any number of derived
classes, such as circles, rectangles and triangles.
➢ No matter what shape an object is, applying the area method to it will
return the correct results.
Types -
There are two types of polymorphism in java:
1) Static Polymorphism also known as compile time polymorphism
2) Dynamic Polymorphism also known as runtime polymorphism
Types -
1. Static Polymorphism
➢ Polymorphism that is resolved during compiler time is known as static
polymorphism.
➢ It means that ,when the compiler is able to determine the actual
function, it’s called compile-time polymorphism.
➢ There are two types of compile-time polymorphism.
○ Method Overloading
○ Operator Overloading
2. Dynamic Polymorphism
➢ Dynamic polymorphism is a process in which a call to an overridden
method is resolved at runtime, that's why it is called runtime
polymorphism.
○ Method overriding
Overloading:
● Same action, but you do it in different ways (like serving different food
courses).
● Think of overloading like having the same action or task, but with different
ways to do it depending on the situation.
Booking a ticket for a flight
public void book(String destination)
Booking a ticket with a meal
public void book(String destination, String meal)
Booking a family ticket
public void book(String destination, int peopleCount)
Method Overloading -
➢ It is type of Static Polymorphism
➢ In Java, it is possible to define two or more methods within the same
class that share the same name, as long as their parameter declarations
are different. When this is the case, the methods are said to be
overloaded, and the process is referred to as method overloading.
➢ Overloaded methods must differ in the type and/or number of their
parameters.
➢ While overloaded methods may have different return types, the return
type alone is insufficient to distinguish two versions of a method.
➢ When Java encounters a call to an overloaded method, it simply
executes the version of the method whose parameters match the
arguments used in the call.
Method Overloading - Sample program
Based on number of parameters
Example 1: Overloading – Different Number of parameters in argument list

class DisplayOverloading{
public void disp(char c) {
System.out.println(c); }
public void disp(char c, int num) {
System.out.println(c + " "+num); } }
class Sample {
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}}
Method Overloading - Sample program
Based on number of parameters
Example 2: Overloading – Difference in data type of parameters

class DisplayOverloading2 {
public void disp(char c) {
System.out.println(c); }
public void disp(int c) {
System.out.println(c ); } }
class Sample2 {
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}}
Method Overloading - Sample program
Based on number of parameters
Example3: Overloading – Sequence of data type of arguments

class DisplayOverloading3 {
public void disp(char c, int num) {
System.out.println("I’m the first definition of method disp"); }
public void disp(int num, char c) {
System.out.println("I’m the second definition of method disp" );
}}
class Sample3 {
public static void main(String args[]) {
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
}}
Method Overloading and Type Promotion
What is Automatic Type Promotion?
The name Type Promotion specifies that a small size datatype can be promoted to a large size
datatype. i.e., an Integer data type can be promoted to long, float, double, etc. This Automatic
Type Promotion is done when any method which accepts a higher size data type argument is
called with the smaller data type
Example:
public static void method(double a){
System.out.println("Method called");
}

public static void main(){


method(2);
}
In the above method call, we passed an integer as an argument, but no method accepts an
integer in the below code. The Java compiler won’t throw an error because of the Automatic
Type Promotion. The Integer is promoted to the available large size datatype, double.
This is important to
remember is
Automatic Type
Promotion is only
possible from small
size datatype to higher
size datatype but not
from higher size to
smaller size. i.e.,
integer to character is
not possible.
Method Overloading and Type Promotion
class Demo{
void disp(int a, double b){
System.out.println("Method A"); }
void disp(int a, double b, double c){
System.out.println("Method B"); }
public static void main(String args[]){
Demo obj = new Demo();
/* float value is passed as a second argument but
* it got promoted to the type double, because there
* wasn't any method having arg list as (int, float)
*/
obj.disp(100, 20.67f);
}}
Method Overloading and Type Promotion
class Demo1{
void disp(int a, double b){
System.out.println("Method A"); }
void disp(int a, double b, double c){
System.out.println("Method B"); }
void disp(int a, float b){
System.out.println("Method C"); }
public static void main(String args[]){
Demo1 obj = new Demo1();
/* This time promotion won't happen as there is
* a method with arg list as (int, float)
*/
obj.disp(100, 20.67f);
Method Overloading - Sample program
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters"); }
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b); }
// Overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a; }
Method Overloading - Sample program
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Advantage of Method overloading
❏ The main advantage is cleanliness of code.
by reducing the need for different method names for performing similar tasks

❏ Increases the readability of the program.


It is easier to understand that add() works for both integers and doubles rather than
having to decipher multiple method names like addInt(), addDouble(), etc.

❏ Overloaded methods give programmers the flexibility to call a similar method for
different types of data.
You don't need to write separate logic for every data type that you want to process.

❏ Overloading is also used on constructors to create new objects given different


amounts of data.
This avoids creating multiple classes
allows creating objects in different ways
❏ Reduces execution time because the binding is done during compilation time.

❏ Achieves flexibility.
Overloaded methods allow you to perform similar actions with various types of
data, which adds flexibility in how the program behaves without changing method
names.
❏ Code reusability ; hence it saves memory.
you can reuse the same method, passing different arguments to suit the need

❏ Code complexity is reduced. Hence provides consistency of code.


Overloading prevents a situation where you have to remember and use different
method names for every combination of data types.
❏ You must define a return type for each overloaded method. Methods can have
different return types
developers can easily understand that the operations performed are similar and
just differ in the type or number of arguments.
Overloading Constructors

What is need of Overloading


Constructor?
As you can see, the Box()
constructor requires three
parameters.
This means that all declarations of
Box objects must pass three
arguments to the Box() constructor.

So the following statement is


currently invalid:

Box ob = new Box();


Overloading Constructors
What if you simply wanted a box and did not care (or know) what its
initial dimensions were?
Or, what if you want to be able to initialize a cube by specifying only one
value that would be used for all three dimensions?

As the Box class is currently written, these other options are not available
to you.
Fortunately, the solution to these problems is quite easy: simply overload
the Box constructor so that it handles the situations just described. Here is
a program that contains an improved version of Box that does just that:
Overloading Constructors - example
Parameters and Arguments
Parameters and Arguments

Parameter:
○ Any information that you need to pass to a method is received
by variables specified within the set of parentheses that follow
the name of the method.
○ These variables are called parameters.

○ A parameter is a variable defined by a method that receives a


value when the method is called.

Arguments:
● An argument is a value that is passed to a method when it is
invoked.
Passing values to a Method - Parameters
➢ Input values for methods (within the program, not from user)
○ passed values or parameters
➢ More flexibility for methods
1.Formal parameters
○ Part of method definition
○ After the method name, within parentheses
■ type
■ name
2.Arguments, or actual parameters
➢ Calling a method with an object within the parentheses
○ matching data type
○ in the same order
Parameter and Argument

//Method square
int square(int i)
{
i is a formal parameter
return i * i;
}

square(100); 100 as an argument or actual parameters


Scope of Formal Parameters

Start: begin of the method


End: end of the method

public float square(float num)


{ // begin of num’s scope

} // end of num’s scope
Argument passing example

//Definition of method to double an integer


public int doubleValue(int numberIn)
{
return 2 * numberIn;
}

//Invocation of the method... somewhere in main...


...
int next = keyboard.nextInt();
System.out.println(someObj.doubleValue(next));
Argument passing example

//Definition of method to double an integer


public int doubleValue(int numberIn)
{
return 2 * numberIn;
}

//Invocation of the method... somewhere in main...


...
int next = keyboard.nextInt();
System.out.println(someObj.doubleValue(next));

1.What is the formal parameter in the method definition?


2.What is the argument (actual parameter) in the method invocation?
Type of Argument passing
A computer language can pass an argument to a subroutine by two ways
Call by value:
This approach copies the value of an argument into the formal parameter of the
subroutine. Therefore, changes made to the parameter of the subroutine have no
effect on the argument.

Call by Reference: In this approach, a reference to an argument (not the value of


the argument) is passed to the parameter.
Inside the subroutine, this reference is used to access the actual argument specified
in the call.
This means that changes made to the parameter will affect the argument used to
call the subroutine.

As you will see, although Java uses call-by-value to pass all arguments, the precise
effect differs between whether a primitive type or a reference type is passed.
Type of Argument passing
Type of Argument passing

Call-by-value:
When you pass a primitive type to a method, it is passed by value.
Thus, a copy of the argument is made, and what occurs to the
parameter that receives the argument has no effect outside the method.
Example -

a and b before call: 15 20


a and b after call: 15 20
Call By Reference:
➢ In this approach, a reference to an argument (not the value of the argument) is
passed to the parameter.

➢ Inside the subroutine, this reference is used to access the actual argument
specified in the call. This means that changes made to the parameter will
affect the argument used to call the subroutine.

➢ As you will see, although Java uses call-by-value to pass all arguments, the
precise effect differs between whether a primitive type or a reference type is
passed.

➢ When you pass an object to a method, the situation changes dramatically,


because objects are passed by what is effectively call-by-reference
Example - Call by reference

This program generates the following


output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
Type of Argument passing
Polymorphism

2. Method Overriding:

• Multiples implementations of the same method occur in different


classes along the same hierarchy.
• A child class “overrides” the implementation of a method
provided by its base class.
• Examples:
– Cat.makeNoise( ) overrides Animal.makeNoise( )
Overriding vs. Overloading
• Do not confuse overriding with overloading

▪ Overriding takes place in the subclass – new method with


same signature

▪ Overloading takes place in the same class or subclass –


new method with different signature
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.

● Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

● method must have same name as in the parent class


● method must have same parameter as in the parent class.
● must be IS-A relationship (inheritance).
Problem without method overriding
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
public static void main(String args[])
{ If we do not have
Bike obj = new Bike(); overriding method
obj.run();
in child class
}
}

Output:Vehicle is running
Method Overriding
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}

class Bike2 extends Vehicle


{
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
obj.run();
}
Output:Bike is running safely
Method Overloading Method Overriding

Method overloading is a compile-time


Method overriding is a run-time polymorphism.
polymorphism.

Method overriding is used to grant the specific implementation


Method overloading helps to increase the
of the method which is already provided by its parent class or
readability of the program.
superclass.

It occurs within the class. It is performed in two classes with inheritance relationships.

Method overloading may or may not require


Method overriding always needs inheritance.
inheritance.

In method overloading, methods must have the In method overriding, methods must have the same name and
same name and different signatures. same signature.
In method overloading, the return type can or can
In method overriding, the return type must be the same or
not be the same, but we just have to change the
co-variant.
parameter.

Static binding is being used for overloaded


Dynamic binding is being used for overriding methods.
methods.

Poor Performance due to compile time It gives better performance. The reason behind this is that the
polymorphism. binding of overridden methods is being done at runtime.

Private and final methods can be overloaded. Private and final methods can’t be overridden.

The argument list should be different while doing


The argument list should be the same in method overriding.
method overloading.
There are three kinds of variables in Java:
1. Local variables

2. Instance variables

3. Class/static variables
class A
{

int data=50; //instance variable

static int m=100; //static variable

void method()
{

int n=90; //local variable


}

}
Local variables

❏ Local variables are declared in methods, constructors, or blocks.

❏ Local variables are created when the method, constructor or block is


entered and the variable will be destroyed once it exits the method,
constructor or block.

❏ Access modifiers cannot be used for local variables.

❏ Local variables are visible only within the declared method, constructor or
block.

❏ There is no default value for local variables so local variables should be


declared and an initial value should be assigned before the first use.
Instance variables
■ Instance variables are declared in a class, but outside a method,
constructor or any block.

■ Instance variable doesn't get memory at compile time.

■ It gets memory at runtime when object(instance) is created.That is


why, it is known as instance variable.

■ Instance variables are created with the use of the keyword 'new' and
destroyed when the object is destroyed (when object is garbage
collected).

■ Access modifiers can be given for instance variables.

■ Instance variables have default values. For numbers the default


value is 0, for Booleans it is false and for object references it is null.
class Student1
{
int id; //data member (also instance variable)
String name; //data member(also instance variable)

public static void main(String args[])


{
Student1 s1=new Student1(); //creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Class/static variables

1. Static variables are declared with the static keyword in a class, but outside a
method, constructor or a block.

2. They are known as Class level variable because values of these variables are
not specific to any instance but are common to all instances of a class. Such
variables will be shared by all instances of an object.

3. The static variable gets memory only once in class area at the time of class
loading.

4. Default values are same as instance variables. For numbers, the default value
is 0; for Booleans, it is false; and for object references, it is null
Instance variable hiding -

1. It is illegal in Java to declare two local variables with the same name
inside the same or enclosing scopes.

2. Interestingly, you can have local variables, including formal parameters


to methods, which overlap with the names of the class’ instance
variables.

3. However, when a local variable has the same name as an instance


variable, the local variable hides the instance variable.
public void display()
class Super { {
String name = "Krishna"; Sub obj = new Sub();
int age = 25; System.out.println("Name: "+obj.name);
} System.out.println("age: "+obj.age);
class Sub extends Super }

{ String name = "Vishnu"; }

int age = 22; public class FieldHiding{

public static void main(String args[]){

new Sub().display();

}
Name: Vishnu
age: 22
The keyword - this

1. The this keyword used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword
resolves the problem of ambiguity.
2. this can also be used to:
a. Invoke current class constructor
b. Invoke current class method
c. Return the current class object
d. Pass an argument in the method call
e. Pass an argument in the constructor call
If local variables(formal arguments) and instance variables
are different, there is no need to use this keyword
class Student class TestThis3
{ {
int rollno; public static void main(String args[])
String name; {
float fee; Student s1=new Student(111,"ankit",5000f);
Student(int r,String n,float f) Student s2=new Student(112,"sumit",6000f);
{ s1.display();
rollno=r; s2.display();
name=n; }
fee=f; }
}
void display() Output:
{ 111 ankit 5000.0
System.out.println(rollno+" +name+" "+fee); 112 sumit 6000.0
}
}
Problem without this keyword
class TestThis1
class Student {
{ public static void main(String args[])
int rollno; {
String name; Student s1=new
float fee; Student(111,"ankit",5000f);
Student(int rollno,String name,float fee) Student s2=new
{ Student(112,"sumit",6000f);
rollno=rollno; s1.display();
name=name; s2.display();
fee=fee; }
} }
void display(){System.out.println(rollno+" "
+name+" "+fee);} Output:
}
0 null 0.0
0 null 0.0
Parameters (formal arguments) and instance variables are same. So, this
keyword is used to distinguish local variable and instance variable

class Student class TestThis2


{ {
int rollno; public static void main(String args[])
String name; {
float fee; Student s1=new Student(111,"ankit",5000f);
Student(int rollno,String name,float fee) Student s2=new Student(112,"sumit",6000f);
{ s1.display();
this.rollno=rollno; s2.display();
this.name=name; }
this.fee=fee; }
}
void display() Output:
{ 111 ankit 5000.0
System.out.println(rollno+" "+name+" "+fee);} 112 sumit 6000.0
}
Using keyword - this with class attribute(x)
public class Main {
int x;
// Constructor with a parameter
public Main(int x)
{
x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}
OutPut:Value of x = 0
Using keyword - this with class attribute(x)
public class Main {
int x;
// Constructor with a parameter
public Main(int x)
{
this.x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
OutPut:Value of x = 5
}
Java static variable
● If any variable is declared as static, it is known as a
static variable.
● The static variable can be used to refer to the common
property of all objects (which is not unique for each
object), for example, the company name of employees,
college name of students, etc.

● The static variable gets memory only once in the class


area at the time of class loading.
Problem without static variable
saving memory and
making it easier to
class Student{ maintain a single shared
int rollno; value.
String name;
college is the same for
String college="ITS"; every student, so it makes
} sense to make it static.

rollno and name are


instance-specific, so they
should not be static.
class Student //Test class to show the values of objects
{ public class TestStaticVariable1
int rollno; //instance variable {
String name; public static void main(String args[])
static String college ="ITS"; //static variable {
Student(int r, String n) //constructor Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
{
rollno = r; //we can change the college of all objects by the
name = n; single line of code
} //Student.college="BBDIT";
void display () //method to display the values
{ s1.display();
System.out.println(rollno+" "+name+" "+college);} s2.display();
} }
}

Output:
111 Karan ITS
222 Aryan ITS
Understanding static -

1. There will be times when you will want to define a class member
that will be used independently of any object of that class.

2. Normally, a class member must be accessed only in conjunction


with an object of its class. However, it is possible to create a
member that can be used by itself, without reference to a specific
instance.

3. To create such a member, precede its declaration with the keyword


static.
Understanding static -

1. When a member is declared static, it can be accessed before any


objects of its class are created, and without reference to any object.

2. The most common example of a static member is main( ). main( ) is


declared as static because it must be called before any objects exist.

3. Instance variables declared as static are, essentially, global variables.


When objects of its class are declared, no copy of a static variable is
made. Instead, all instances of the class share the same static variable.
Java static method
If you apply static keyword with any method, it is known
as static method.
1. A static method belongs to the class rather than the object
of a class.

2. A static method can be invoked without the need for


creating an instance of a class.

3. A static method can access static data member and can


change the value of it.
class Student
{
/Test class to create and display the values of object
int rollno; public class TestStaticMethod
String name; {
static String college = "ITS"; public static void main(String args[])
//static method to change the value of static {
variable Student.change(); //calling change method
static void change() //creating objects
Student s1 = new Student(111,"Karan");
{
Student s2 = new Student(222,"Aryan");
college = "BBDIT"; Student s3 = new Student(333,"Sonoo");
} //calling display method
//constructor to initialize the variable s1.display();
Student(int r, String n) s2.display();
{ s3.display();
}
rollno = r;
}
name = n;
} Output:111 Karan BBDIT
//method to display values 222 Aryan BBDIT
void display() 333 Sonoo BBDIT
{
System.out.println(rollno+" "+name+" "+college);}
}
Java Program to get the cube of a given number using the
static method
class Calculate{
static int cube(int x){
return x*x*x;
}

public static void main(String args[]){


int result=Calculate.cube(5);
System.out.println(result);
}
}
Output:125
Understanding static -

1. Methods declared as static have several restrictions:

2. They can only directly call other static methods and They can

only directly access static data.(The static method can not use non

static data member or call non-static method directly.)

3. They cannot refer to this or super (refer to the immediate parent

class object )in any way.


Inside main(),
A a1 =new A();
class A{ System.out.println(a1.a);
int a=40;//non static

public static void main(String args[]){


System.out.println(a);
}
}
Output:Compile Time Error
Java static block
● Is used to initialize the static data member.
● It is executed before the main method at the time of classloading.
Example of static block
class A2{
static{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}
Output:static block is invoked
Hello main
Understanding static -

Static block initialized.


x = 42
a = 3
b = 12
Understanding static -

Within the same class- If the static variable belongs to the same class, you can access it directly without
using the class name.

In a different class-You must use the class name to access the static variable of another class.
Final Keyword

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
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).

class Bike9{

final int speedlimit=90; //final variable

void run(){

speedlimit=400;

public static void main(String args[]){

Bike9 obj=new Bike9();

obj.run();

}//e
Output:Compile Time Error
2) Java final method
public static void main(String args[]){

Honda honda= new Honda();

If you make any method as final, you cannot override it. honda.run();

class Bike{ }
final void run() }
{ Output:Compile Time Error
System.out.println("running");}

class Honda extends Bike{

void run()

System.out.println("running safely with 100kmph");

}
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();

honda.run();

}
Output:Compile Time Error

You might also like