-2
import java.util.Random;

class VehicleConstructor{

    private int startSpeed;

    public VehicleConstructor() {
        setSpeed();
        System.out.println("VehicleConstructor");
    }

    private void setSpeed(){
        int minSpeed = 1;
        int maxSpeed = 40;

        Random random = new Random();
        this.startSpeed = random.nextInt(maxSpeed - minSpeed + 1) + minSpeed;
    }
}

class Bicycle extends Vehicle{

    public Bicycle(){
        System.out.println(getSpeed());
    }
}

public class Vehicle{
    public static void main(String[] args){
        Bicycle bicycle = new Bicycle();
    }
}

问题出在Bicycle课堂上,我尝试getSpeed()从课堂上调用方法VehicleConstructor。我也用thisand试过了super。怎么了?

4

6 回答 6

2

getSpeed您提供的代码中没有命名方法- 只有一个setSpeed- 并且该方法是private,这意味着它不能从任何外部类访问。

于 2012-12-26T21:03:17.483 回答
2

您的Bicycle课程目前扩展Vehicle,而不是VehicleConstructor。扩展VehicleConstructor,并创建一个getSpeed()方法,您的问题应该得到解决。

于 2012-12-26T21:03:19.007 回答
0

setSpeed()是一种方法VehicleConstructor,不是Vehicle

但是,如果它是拼写错误并且getSpeed()是 的方法Vehicle,您仍然无法访问它,因为它被声明为private. 访问父方法所需的最小访问修饰符是protected.

于 2012-12-26T21:04:07.617 回答
0

似乎getSpeed()没有在VehicleConstructor类中定义!!!

于 2012-12-26T21:04:53.920 回答
0

也许你想要这个:

public class Vehicle{
    private int speed;
    public  void setSpeed(int speed){
        this.speed=speed;
    }

    public int getSpeed() {
        return speed;
    }
}
于 2012-12-26T21:06:12.390 回答
0

我想你想要更多这样的东西:

 class Vehicle{

    private int startSpeed;

    public Vehicle() {
        setSpeed();
        System.out.println("Vehicle");
    }

    private void setSpeed(){
        int minSpeed = 1;
        int maxSpeed = 40;

        Random random = new Random();
        this.startSpeed = random.nextInt(maxSpeed - minSpeed + 1) + minSpeed;
    }
    public int getSpeed(){ 
        return startSpeed; 
    } 
}

public class bicycle extends Vehicle{

    public Bicycle(){
        System.out.println(super.getSpeed());
    }

}

public class VehicleCostructor{

    public static void main(String[] args){
        Bicycle bicycle = new Bicycle();

    }
}

假设您的 VehicleConstructor 应该只是对您的课程的测试。

一个更好的测试方法可能是使用 JUnit。是一个非常有用且易于使用的工具。

希望这有帮助!

于 2012-12-26T21:29:43.197 回答