Unit 2_Polymorphism
Unit 2_Polymorphism
Polymorphism
➢ Polymorphism (from Greek, meaning “many forms”) is a feature that
allows one interface to be used for a general class of actions.
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");
}
❏ 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.
❏ 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
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.
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;
}
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 -
➢ 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.
2. Method Overriding:
Output:Vehicle is running
Method Overriding
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
It occurs within the class. It is performed in two classes with inheritance relationships.
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.
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.
2. Instance variables
3. Class/static variables
class A
{
void method()
{
}
Local variables
❏ Local variables are visible only within the declared method, constructor or
block.
■ Instance variables are created with the use of the keyword 'new' and
destroyed when the object is destroyed (when object is garbage
collected).
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.
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
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. They can only directly call other static methods and They can
only directly access static data.(The static method can not use non
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
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{
void run(){
speedlimit=400;
obj.run();
}//e
Output:Compile Time Error
2) Java final method
public static void main(String args[]){
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");}
void run()
}
3) Java final class
If you make any class as final, you cannot extend it.
honda.run();
}
Output:Compile Time Error