What is overriding?
We have discussed about overloading in the the previous post. Now we will discuss about overriding and its differences with overloading.
Overriding allows us to modify a method behavior at run time.
Overriding allows us to modify a method behavior at run time.
Here are the rules to make 2 overridden methods:
1. Methods must not take its arguments different. Here if a method is taking object of Class A then another method which is taking object of [Class B extends A] then it is allowed.
2. Overriding is done with its super class methods only.
3. Overriding does not allow overriding method to throw a new checked exception or a super class of the exception class that overridden method is throwing.
Example:
class A{
protected void display() throw SQLException{
}
}
class B extends A{
void display() Exception {
}
void display() IOException {
}
public void display(){
}
}
4. Overloading must not change its return return types. Here if a method is returning object of Class A then another method returning object of [Class B extends A] then it is allowed.
5. Overriding can change the access modifiers but overriding method should have less limiting access permission.
Example:
class A{
protected void display(){
}
}
class B extends A{
default void display(){
}
public void display(){
}
}
*** Red means not allowed and Green means allowed here.
1. Methods must not take its arguments different. Here if a method is taking object of Class A then another method which is taking object of [Class B extends A] then it is allowed.
2. Overriding is done with its super class methods only.
3. Overriding does not allow overriding method to throw a new checked exception or a super class of the exception class that overridden method is throwing.
Example:
class A{
protected void display() throw SQLException{
}
}
class B extends A{
void display() Exception {
}
void display() IOException {
}
public void display(){
}
}
4. Overloading must not change its return return types. Here if a method is returning object of Class A then another method returning object of [Class B extends A] then it is allowed.
5. Overriding can change the access modifiers but overriding method should have less limiting access permission.
Example:
class A{
protected void display(){
}
}
class B extends A{
default void display(){
}
public void display(){
}
}
*** Red means not allowed and Green means allowed here.
No comments:
Post a Comment