2011-12-14

Java method overriding rules?

A method is said to be overriding method if it satisfies the below rules.

1.return type should be same as super class method.

In the below program we should not place return type as int we will get a compile time error, in order to override that method we should place the below method return type as void.

class Example{
   void m1(){ }
}

class Sample extends Example{
   void m1(){ }
}

class Sample extends Example{
   int m1(){ return 10;}
}

2.static modifier should not be removed or added.
class Example{
   void m1(){ }
}

class Sample extends Example{
   static void m1(){}
}

If we place modifier as static in sub class it leads to compile time error in the above program.
class Example{
   static void m1(){ }
}

class Sample extends Example{
   void m1(){}
}

If we should not place modifier as static in sub class it leads to compile time error in the above program.

3.access specifier should be same as super class method or it can be increased,but should not be decreased. The below table shows the allowed access specifiers for the sub class method based on super class method access specifier.

Super class methodSub class method
Privateprivate,default,protected,public(method is not considered as overridden method because it is not inherited)
Packagepackage,protected,public
Protectedprotected,public
Publicpublic

If the super class method is private and if we define the same method in sub class with or without private then the sub class method is not called as overriding method means they are not inherited, only super class's non private members are inherited . We have to keep in mind that constructor,blocks,private members are not inherited. If we are able to call super class members with 'super.' or by using sub class object then we can say they are inherited.

4. throws clause should not be added if super class method does not contain it. If super class method contain throws clause then in sub class, overriding method should contain throws clause with same exception class.

Loading

Enter your Email here: