What restrictions are placed on method overriding?
Below are the listed restrictions:
- Inherits a method from a superclass
- Superclass method is not final
- Superclass method is not private
- Superclass method is not static
- Superclass can be abstract
- Signature must be EXACT SAME
- Overidden method can not be more restrictive
- Overidden method must not throw new or broader checked exceptions
- Call super if overridden
- The return type must be the same as the original overridden method (or a subtype == covariant returns.)
MethodOverridingDemo.java
abstract class Shape
{
String res;
abstract void area();
public void disp()
{
System.out.println(res);
}
}
class Rect extends Shape
{
public void area() //Overriding area()
{ res="Rectangle";
}
}
class Circle extends Shape
{
public void area() //Overriding area()
{ res="Circle";
}
}
class MethodOverridingDemo
{
public static void main(String s[])
{
Rect r=new Rect(); r.area(); r.disp();
Circle c=new Circle(); c.area(); c.disp();
//---The same code written as ----------------
System.out.println("Through Shape class Ref:-");
Shape sh=new Rect();
sh.area();
sh.disp();
sh=new Circle();
sh.area();
sh.disp();
// ---and known as dynamic method dispatch----
}
}
Recent Comments