Orion31 Orion31 - 1 year ago 71
Java Question

Make a child class define an object

I was wondering if there was a way to make a child class of an

class define an object, and in this case an
. This might have a simple answer, and I'm not looking enough, but I can't find anything!
Thank you!

Answer Source

Put the ArrayList as a protected field of the abstract class. Any subclass will be able to access it using the super qualifier, or by name if it isn't being shadowed by a local variable.

public abstract class Person {
    protected List<Person> friends = new ArrayList<>();
    public void callCellPhone() { ... }

public class Student extends Person {
    public void callFriends() {
        // friends is defined in the super-class
        // "super" is an optional qualifier here
        for (Person person : super.friends) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download