How do I call abstract class’ child class method when using an array of child objects?

I have an abstract class(parent class) and its child class.

In main, I created an array. It looks like this:

AbstractClass[] array = {childClassObj1, childClassObj2};
printInfo(array);

public static void printInfo (AbstractClass[] array){
System.out.printf("%s", childClassObj1.getInfo());
}

The compiler error occurs in “childClassObj1.getInfo()”. If I change it to “array[0].getInfo()”, it cannot be done since the method getInfo() is in the child class, not in the abstract class. How do I call abstract class’ child class method?

Answer

Add an abstract method getInfo() to your parent class.

public abstract class AbstractClass {
    public abstract String getInfo();
}

Then, override this method in your child class:

public class ChildClass extends AbstractClass {
    @Override
    public String getInfo() {
        return "Info string";
    }
}

Then, iterate over your array and call that method on each instance:

public static void printInfo (AbstractClass[] array){
    for(AbstractClass child : array) {
        System.out.printf("%s%n", child.getInfo());
    }
}

EDIT: If you can’t add methods to your abstract class, you’ll need to cast each element in your loop to the type of your child class:

public static void printInfo (AbstractClass[] array){
    for(AbstractClass child : array) {
        System.out.printf("%s%n", ((ChildClass)child).getInfo());
    }
}

Be careful though. This will only work if you’re certain that only instances of ChildClass are inside your array. If there are instances of another sub-class you’ll get a ClassCastException.

Also doing it like this kinda defeats the purpose of having an abstract class because you could easily use an array of ChildClass instead if you only need the functionality from there.

Leave a Reply

Your email address will not be published. Required fields are marked *