Ads

Sunday, December 27, 2020

How does method overriding and object polymorphism work in Java inheritance? Can you provide an example?

Here is the code to implement the scenario described


Source Code..


class A {

    public void print() {

        System.out.println("Parent");

    }

}

 

class B extends A {

    public void print() {

        System.out.println("Child");

    }

}

 

public class Main {

    public static void main(String[] args) {

        A a = new A();

        B b = new B();

 

        a.print(); // output: Parent

        b.print(); // output: Child

 

        A a2 = new B();

        a2.print(); // output: Child

    }

}

 Code Explanation:

In this code, we have two classes A and B, where B is a subclass of A. Both classes have a method named print() that prints a string.

 

In the Main class, we create two objects, a of class A and b of class B. We call the print() method on both objects, and the output is "Parent" for object a and "Child" for object b.

 

Then, we create an object a2 of class A but we assign it an object of class B. This is called upcasting, where a subclass object is assigned to a superclass reference. When we call the print() method on a2, the method in the B class is called instead of the method in the A class. This is an example of polymorphism, where the same method name is used in both the superclass and subclass, and the correct method is called based on the type of the object at runtime

 

Concepts that are use in this program:

In this program we use the concepts of inheritance, method overriding, and method invocation.

 

Inheritance is used to create a subclass 'B' that inherits properties and methods from the superclass 'A'. Method overriding is used to override the method in the superclass 'A' with the same name in the subclass 'B'. This allows the subclass to have its own implementation of the method.

The method invocation is used to call the method using objects of both classes 'A' and 'B'. Additionally, the program also shows that an object of the parent class 'A' can be used to refer to the child class 'B', but only if the method is overridden in the child class.


No comments:

Post a Comment