If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
- Method overriding is used to provide the specific (different) implementation of a method which is already provided by its superclass.
- Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
- The method must have the same name as in the parent class
- The method must have the same parameter as in the parent class.
- There must be an IS-A relationship (inheritance).
Example:
class A
{
void display()
{
System.out.println(“ I am super class
method”);
}
}
class B extends A
{
void display()
{
super.display();
System.out.println(“ I am sub
class method”);
}
}
class OverridingDemo
{
public static void mian(String
args[])
{
B
b1=new B();
b1.display();
}
}
In the above the “super” keyword
is used to class super class method. If you can’t use it, only the sub class
method is classed.
In overriding always the sub
class version of method is executed. If you want super class method, then class it suing
“super” keyword.
Constructor
overriding:
·
By
rule in Java, a constructor cannot be overridden but a method can be
overridden.
·
It
looks as if constructor is overridden but not.
·
Constructors
show inheritance like when we make an instance of child class then the
constructor of the parent class gets invoked first.
·
A
by default call to the parent class constructor i.e. super(); which makes call
to the parent class constructor.
·
Overriding
means to redefine the functionality of the method (defined in the parent/base
class) by making the method of same name but with different behavior in the
derived/child class.
REASON :- Why constructor cannot be overridden
?
If we try to override the
constructor of parent class in child class then it won’t be able to identify
the method. Since the scope of constructor is limited to the class itself. When
you define the class again in some other class then it won’t be able to
recognize the signature of the method.
class A
{
A()
{
System.out.println(“ super class
constructor”);
}
}
class B extends A
{
B()
{
super();
System.out.println(“ sub class
constructor”);
}
}
class Demo
{
public static void main(String args[])
{
B
b1=new B();
}
}
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.