Overriding is directly related to OOP with inheritance and subclassing.
Why to override - It is used to modify the behavior by redefining the inherited method in the subclass.
Late binding of method - Java determines the method to be executed based on the type of actual object at runtime. At compile time no object is created yet, hence Java does not predetermine the method to be called at compile time just by looking at the method call. The decision of which method to call is delayed to the runtime as the type of actual object (that the reference variable will hold) is often not known at compile time. When a call is made to overridden method by the variable of superclass and object of subclass, then that method call is determined at runtime.
class MySuperClass{
public void method(){
System.out.println("Super class");
}
}
class MySubClass{
public void method(){
System.out.println("Sub class");
}
}
class MyImplClass{
public static void main(){
MySuperClass obj = new MySubClass();
obj.method();
/*this call is determined at runtime, whether to call super class method or sub class. This will print 'Sub Class', depending on the object used for call which will be created and available at runtime.*/
}
}
Rule for overriding -
1. Same method name along with same type and order of argument. If type and order of argument are not same than its considered as overloading.
2. Return type in java 5 can be narrower mean a subclass, can be returned in the overriding method, of the return type class of overridden method.
3. Access modifier must be less restrictive. This rule is imposed because Java assumes that you do subclassing for extending a class. If Java had allowed you to override a method to be more private, you could have easily made the public methods of superclass inaccessible (in subclass). Effectively you would have restricted the class instead of extending it. Since in Java subclassing is done only to extend a class, you are not allowed to restrict its behavior by overriding the methods to be more private. Private method are not accessible to the subclass hence does not make sense to override.
4. The overridden method may not throw any checked exceptions at all. If it throws, the exception must be either same as the exception thrown by the superclass method or the exception must be a subclass of the exception thrown by the superclass method.
5. final method of super class. Overridding method can be made final.
No comments:
Post a Comment