1

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)

3
  • Why are you making this variable static in the first place? Commented Feb 19, 2015 at 19:38
  • 1
    What do you mean by "simply call the function Vehicle.speed"? That's a field, not a function. And static isn't a type, it's a modifier... Commented Feb 19, 2015 at 19:39
  • 1
    I think you should review the class notes about class (static) vs. instance (non-static) fields. Vehicle.speed as you wrote it is not the speed of a given vehicle. It's the speed of all vehicles, which makes no sense. Commented Feb 19, 2015 at 19:40

1 Answer 1

1

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();  
    }  
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.