我有以下程序:
class Vehicle{
static int speed=50;
Vehicle(){
this.speed=speed;
}
}
class Bike4 extends Vehicle{
int speed=100;
void display(){
System.out.println(Vehicle.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike4 b=new Bike4();
b.display();
}
}
假设我不想使用关键字" super"我只需调用函数" Vehicle.speed"为什么我必须将超类中的变速类型更改为静态?如果我在不使用static关键字的情况下运行程序会发生什么? (再次,假设它编译)
答案 0 :(得分:1)
因为您为Bike4定义了与父车辆不同的速度,所以看起来您想要更改派生值。静态变量不起作用,因为它属于类,而不是实例。我想你想要这样的东西:
public class Vehicle{
protected int speed;
Vehicle(int speed) {
this.speed=speed;
}
}
public class Bike4 extends Vehicle {
public Bike4(int speed) {
super(speed);
}
void display() {
System.out.println(speed);
}
public static void main(String args[]) {
Bike4 b=new Bike4(100);
b.display();
}
}