MethodOverloading
Same
method name and different parameters is called method overloading
It may contain same method name and same parameters with different data types and order(number of arguments)
It occurs in same class.
It provides fast execution than overriding
It may or may not require inheritance
Static method can be overloaded
Example:
compile time polymorphism
class
Cal
{
void add(int a, int b)
{
System.out.println("sum of two
number:"+(a+b));
}
void
add(int a, int b, int c)
{
System.out.println("sum of three
number:"+(a+b+c));
}
}
public
class LearningPoint92
{
public static void main(String args[])
{
Cal c1 = new Cal();
c1.add(50, 20);
c1.add(50,
20, 30);
}
}
OUTPUT:
sum
of two number:70
sum
of three number:100
Method overriding
Same
method name and same parameter is called method overriding
It may contain same method name and same parameters with same data types,return type and order(number of arguments)
It occurs in different class.
It provides slow execution than overloading
It require inheritance
Static method cannot be overridden
Example:
runtime polymorphism
.class A{
public void show(){
System.out.println("Hello");
}
}
public
class B extends A{
public
void show(){
super.show(); //to
call superclass method
System.out.println(" Welcome To
LearningPoint92");
}
public static void main(String args[]){
B a1=new B();
//A a1 = new B();
a1.show();
}
}
OUTPUT:
Hello
Welcome To LearningPoint92
Note:
upcasting
is required in runtime polymorphism. Super class reference refer to subclass
object is called upcasting.you can call subclass method using upcasting
A
a1 = new B();
Where A a1=superclass reference
Where new B () =subclass reference
No comments:
Post a Comment