Reputation: 1437
I have the following program:
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();
}
}
Supposing I don't want to use the keyword "super" and I simply call the function "Vehicle.speed" why do I have to change the type of the variable speed in the superclass to static? What would happen if I run the program without using the static keyword? (again, supposing it compiles)
Upvotes: 1
Views: 60
Reputation: 1277
Because you're defining a different speed for Bike4 as opposed to the parent Vehicle, it looks like you want to change the derived value. A static variable won't work because it belongs to the class, not the instance. I think you want something like this instead:
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();
}
}
Upvotes: 1