如何创建只能由类修改而不能由其实例修改的类变量
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);
}
}
实际输出:
Shepherd
期望的输出:
BullDog
最佳答案
使字段final
保持不变。 static Final
位于类级别。
public class BullDog {
public String name;
public static final String breed = "BullDog";
public BullDog(String name){
this.name = name;
}
}
问题在于继承是不可能的。 Poodle 需要自己的静态品种,而你不能让狗提供品种
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"));
关于java - 如何在类中创建静态变量,该变量只能由类修改,而不能由实例修改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59093769/