简体   繁体   English

从父类访问

[英]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. 我有2个类,一个是其子类继承的抽象类,而子类扩展了该类。

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. 使用父类的原因是为了统一我的构造函数/序列化方法,以接受大量不同的类,它们都有相似的数据,但值却大相径庭。

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.) (根据您的用例调整getID()的可见性。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM