OOP override

11:29


Method Overriding

Child class has the same method as of base class. In such cases child class overrides the parent class method without even touching the source code of the base class. This feature is known as method overriding.


Example:
public class BaseClass
{
    public void methodToOverride() //Base class method
    {
         System.out.println ("I'm the method of BaseClass");
    }
}
public class DerivedClass extends BaseClass
{
    public void methodToOverride() //Derived Class method
    {
         System.out.println ("I'm the method of DerivedClass");
    }
}
public class TestMethod
{
     public static void main (String args []) {
        // BaseClass reference and object
        BaseClass obj1 = new BaseClass(); 
        // BaseClass reference but DerivedClass object
        BaseClass obj2 = new DerivedClass(); 
        // Calls the method from BaseClass class
        obj1.methodToOverride(); 
        //Calls the method from DerivedClass class
        obj2.methodToOverride(); 
     }
}

Output:


I'm the method of BaseClass
I'm the method of DerivedClass


Rules for Method Overriding:
1.applies only to inherited methods
2.object type (NOT reference variable type) determines which overridden method will be used at runtime
3.Overriding method can have different return type (refer this)
4.Overriding method must not have more restrictive access modifier
5.Abstract methods must be overridden
6.Static and final methods cannot be overridden
7.Constructors cannot be overridden
8.It is also known as Runtime polymorphism.

Super keyword in Overriding:


When invoking a superclass version of an overridden method the super keyword is used.
Example:

public class BaseClass
{
    public void methodToOverride() //Base class method
    {
         System.out.println ("I'm the method of BaseClass");
    }
}
public class DerivedClass extends BaseClass
{
    public void methodToOverride() //Derived Class method
    {
         System.out.println ("I'm the method of DerivedClass");
    }
}
public class TestMethod
{
     public static void main (String args []) {
        // BaseClass reference and object
        BaseClass obj1 = new BaseClass(); 
        // BaseClass reference but DerivedClass object
        BaseClass obj2 = new DerivedClass(); 
        // Calls the method from BaseClass class
        obj1.methodToOverride(); 
        //Calls the method from DerivedClass class
        obj2.methodToOverride(); 
     }
}

Output:
I'm the method of BaseClass
I'm the method of DerivedClass

You Might Also Like

0 nhận xét

Popular Posts

Like us on Facebook

Flickr Images

Subscribe