Java: static field in abstract class

后端 未结 8 1112
独厮守ぢ
独厮守ぢ 2020-12-24 01:04

I just start out with an example, that explains it best:

public abstract class A{
    static String str;
}

public class B extends A{
    public B(){
                


        
8条回答
  •  遥遥无期
    2020-12-24 01:27

    Put the static varibale in each subclass and add a (not static) abstract method to the abstract superclass:

    abstract String getStr();
    

    Then implement the getStr() method in each subclass by returning the static field of this special subclass.

    public class B extends A {
     private static String str;
    
      @Override
      public String getStr() {
        return B.str;
      }
    }
    

提交回复
热议问题