How can we create object for inherited class in java.

In Java, creating an object for an inherited class is similar to creating an object for any other class. However, there are a few things to keep in mind when working with inherited classes.

To create an object for an inherited class, you first need to create the superclass object. This is done using the "super" keyword in the subclass constructor. Once you have created the superclass object, you can use it to access any public or protected methods or variables in the superclass.

Here is an example of how to create an object for an inherited class in Java:

 

public class SuperClass {
    public void display() {
        System.out.println("This is the SuperClass");
    }
}

public class SubClass extends SuperClass {
    public void display() {
        System.out.println("This is the SubClass");
    }
}

public class Main {
    public static void main(String[] args) {
        SubClass subObj = new SubClass();
        subObj.display();
    }
}

In this example, the SubClass extends the SuperClass. The display() method is overridden in the SubClass to print "This is the SubClass".

To create an object for the SubClass, you simply call the new keyword on the SubClass. The display() method in the SubClass is called and the output is "This is the SubClass".

In summary, to create an object for an inherited class in Java, you create the superclass object using the super keyword in the subclass constructor and then use it to access any public or protected methods or variables in the superclass.

Submit Your Programming Assignment Details