java 静态抽象类,Java:抽象类中的静态字段

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(){

str = "123";

}

}

public class C extends A{

public C(){

str = "abc";

}

}

public class Main{

public static void main(String[] args){

A b = new B();

A c = new C();

System.out.println("b.str = " + b.str);

System.out.println("c.str = " + c.str);

}

}

This will print out:

b.str = abc

c.str = abc

But I would like a solution where each subclass that instantiate the super class, has their own class variable, at the same time I want to be able to reference that class variable through the identifier, or a method call, defined in the abstract super class.

So I would like the output to be:

b.str = 123

c.str = abc

Is that doable?

解决方案

If you want classes B and C to have separate static variables, you'll need to declare the variables in those classes. Basically, static members and polymorphism don't go together.

Note that accessing static members through references is a really bad idea in terms of readability - it makes it look like it depends on the value of the reference, when it doesn't really. So your current code won't even compile when you've moved str down to B and C. Instead, you'll need

System.out.println("b.str = " + B.str);

System.out.println("c.str = " + C.str);

If you really need to access the value polymorphically (i.e. through an instance of A) then one option is to make a polymorphic getter:

public class A {

public abstract String getStr();

}

public class B extends A {

private static String str = "b";

@Override public String getStr() {

return str;

}

}

(and the same for C).

That way you get the behaviour you want in terms of not having a separate variable per instance, but you can still use it polymorphically. It's a little odd for an instance member to return a static value like this, but you're using the value for polymorphism of type, basically...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值