[英]How to make static variables inside a class, which can only be modified by the class only and not it's instances?
How to create a class variable which can only be modified by the class only and not it's instances如何创建一个只能由类而不是它的实例修改的类变量
class BullDog{
String name;
static String breed = "BullDog";
public BullDog(String name){
this.name = name;
}
}
public class MainClass{
public static void main(String [] args){
Dog Mydog = new BullDog("Fluffy");
Mydog.breed = "Shepherd"; // Should not be modified
System.out.Println(Dog.breed);
}
}
Real Output:实际输出:
Shepherd
Desired Output:期望输出:
BullDog
Make the field final
that is constant.使字段
final
成为常量。 And static final
is on class level. static final
是在类级别。
public class BullDog {
public String name;
public static final String breed = "BullDog";
public BullDog(String name){
this.name = name;
}
}
The problem is that inheritance is not possible.问题是继承是不可能的。 A Poodle needs its own static breed, and you cannot have a Dog providing a breed
贵宾犬需要自己的静态品种,而您不能让狗提供品种
public abstract class Dog {
public String name;
public Dog(String name){
this.name = name;
}
public abstract String getBreed();
}
public class BullDog extends Dog {
public BullDog(String name){
super(name);
}
@Override
public String getBreed() {
return "Bulldog";
}
}
public class Poodle extends Dog {
public Poodle(String name){
super(name);
}
@Override
public String getBreed() {
return "Wolf";
}
}
List<Dog> dogs = Arrays.asList(new BullDog("fluffy"), new Poodle("Herman"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.