bananas
bananas

Reputation: 1196

How to access all child methods using one single object?

I have a query : we can access all methods from child class using down casting consider following code Base Class :

public class BaseClass {

    public void method() {
        System.out.println("Base class");
    }
}

ChildOne :

public class ChildOne extends BaseClass {
    @Override
    public void method() {
        System.out.println("inside ChildOne");
    }
}

ChildTwo:

public class ChildTwo extends BaseClass {

    @Override
    public void method() {
        System.out.println("inside ChildTwo");
    }
}

And client class

try {
    List l = new ArrayList();
    l.add(new BaseClass());
    l.add(new ChildOne());
    l.add(new ChildTwo());

    for (Object o : l) {
        BaseClass bc = (BaseClass) Class.forName(o.getClass().getName().toString()).newInstance();
        bc.method();
    }
} catch (Exception e) {

}

outPut :

Base class
inside ChildOne
inside ChildTwo

now the question what if

public abstract class BaseClass {

        public abstract void method(); 
    }

as we cannot create object of either interface or of abstract class. In above code I'm able to access all methods from all classes. Consider we've interface named BaseClass with method definition as I am I'm implementing that interface in many classes now the question is how I can access all methods without creating particular instance of every class I want to do that in single loop but inheritance won't allow us How to do that?

Upvotes: 0

Views: 53

Answers (1)

Andrew
Andrew

Reputation: 49646

You need to use a list with generic type (BaseClass): List<BaseClass> l = new ArrayList<>();

Polymorphism is in action, the loop will look like:

for (BaseClass o : l) o.method();

Upvotes: 2

Related Questions