Concept of Method Overriding in Java

Mannan Ul Haq
0

Method overriding is a feature in Java that allows a subclass to provide a different implementation for a method that is already defined in its superclass. This allows the subclass to inherit all methods from the superclass and then choose to change the behavior of some methods based on its specific requirements.


To override a method in Java, the following conditions must be met:


1. Inheritance: The subclass must inherit from the superclass.


2. Method Signature: The method in the subclass must have the same name, return type, and parameter list as the method in the superclass.


3. Access Modifier: The access level cannot be more restrictive than the overridden method's. For example, a public method in the superclass cannot be overridden as a private or protected method in the subclass.


4. final methods: Methods that are declared as final in the superclass cannot be overridden in the subclass.


5. static methods: static methods cannot be overridden. If a subclass defines a static method with the same signature as a static method in the superclass, it is a method hiding, not overriding.


Example:


class Parent
{
    public void print()
    {
        System.out.println("This is print method of the Parent class.");
    }
}

class Child extends Parent
{
    // This method overrides print() of Parent
    public void print()
    {
        System.out.println("This is print method of the Child class.");
    }
}

public class Main
{
    public static void main(String[] args)
    {
        Child child = new Child();
        child.print();  // This calls the print() method of Child
    }
}


Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !