METHOD OVERRIDING IN JAVA IN THE SIMPLEST TERMsteemCreated with Sketch.

in #java4 years ago

Consider the following code. Here the child class inherits the method from parent class. Now when we create the object of child class by commenting its method, we can call the method of parent class and the output shows "In parent class". But when we write same method in the child class but different printing operation, we get the output as "In child class". That is called method overriding. The child class method overrides the parent class method.

package Polymorphism;

class parent{
    public void display() {
        System.out.println("In parent class");
    }
}

class child extends parent{
    /*
    public void display() {
        System.out.println("In child class");
    }
    */
}

public class MethodOverriding {

    public static void main(String[] args) {
        child ch1=new child();
        ch1.display();

    }
}



1.png

Now I had the comment removed.


2.png

If you want to display the output of both the class then you can use "super" keyword. And you should use it in the class that is overriding the another class.

Coin Marketplace

STEEM 0.19
TRX 0.15
JST 0.029
BTC 63350.70
ETH 2595.60
USDT 1.00
SBD 2.85