A_Elric
A_Elric

Reputation: 3568

Accessing from a parent class

I have a bit of a problem that I can't seem to code my way out of for the moment.

I have 2 classes, one is an abstract class that its children inherit from, and the children extend that class.

So it's something like this:

abstract class foo implements Runnable{
    int whatever;
    int whatever2;

    public void doStuff(){

        //need value from child class here -- should be 100
}

public class bar extends foo{
    private int ID = 100;

    //getter here
}

The reason to use a parent class is to unify my constructors / serialization methods to accept tons of different classes that all have similar data but with wildly different values.

Upvotes: 0

Views: 66

Answers (1)

NPE
NPE

Reputation: 500167

Use a method:

public abstract class Foo {

    public void doStuff(){
        int id = getID(); // <==== get the ID
    }

    public abstract int getID();
}

public class Bar extends Foo {

    private int ID = 100;

    public int getID() {
      return ID;
    }
}

(Adjust the visibility of getID() as appropriate for your use case.)

Upvotes: 3

Related Questions