A method in a
subclass has the same name, type of the variables and order of the variables as
a method in its super class, then the method in the subclass is said to be
override the method in the super class.
The process is called Method Overriding.
In such process the method defined by the super class will be hidden.
When the method is called, the
method defined in the super class has invoked and executed instead of the
method in the super class. The super
reference followed by the dot (.) operator may be used to access the original
super class version of that method from the subclass.
Note:
1. Method
Overriding occurs only when the name and type signature of the two methods are
identical.
2. If
method name is identical and the type signature is different, then the process
is said to be Method Overloading.
Example
1:
class
A
{
int i,j;
public A(int a,int b)
{
i=a;
j=b;
}
void show()
{
System.out.println("i="+i+"\n"+"j="+j);
}
}
class
B extends A
{
int k;
B(int a,int b,int c)
{
super(a,b);
k=c;
}
void show()
{
System.out.println("k="+k);
}
}
class
override
{
public static void main(String[]
args)
{
B obj=new B(1,2,3);
obj.show();
}
}
O/P: k=3
Example 2:
class
A
{
int i,j;
public A(int a,int b)
{
i=a;
j=b;
}
void show()
{
System.out.println("i="+i+"\n"+"j="+j);
}
}
class
B extends A
{
int k;
B(int a,int b,int c)
{
super(a,b);
k=c;
}
void show()
{
super.show();
System.out.println("k="+k);
}
}
class
override
{
public static void main(String[]
args)
{
B obj=new B(1,2,3);
obj.show();
}
}
O/P: i=1
j=2
k=3
Resolve the method call at
compile time is known as “compile time” or “early binding” or “static
binding”. Resolve the method at run time
is known as “run time” or “late binding” or “dynamic binding”.
Method Overriding forms on the basis
of Java concept Dynamic Method Dispatch.
It is the mechanism by which a call to an overridden function is
resolved at run time, rather than compile time.
And this method is very useful to show for Java implements run-time
polymorphism.
“Super class reference variable can
refer to a subclass object” is the principle to resolve calls to overridden
methods at run time. If a super class
contains a method that is overridden by a subclass, then when different types
of objects are referred to through a super class reference variable, different
version of the methods are executed and the determination is made at run time.
No comments:
Post a Comment