-1

所以我从 Java 的教程 ( http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) 中复制了 MountainBike、RoadBike、TestBikes 类。

然后我制作了“Bicycle.java”..但是如果我尝试通过使其成为主类来使其执行,那么它甚至不会编译(大量非法的表达式开始。)

无论如何要使它与从该类继承属性的所有类一起编译?

   public class Bicycle {
    public static void main(String[] args) {
        int cadence;
       int gear;
        int speed;

    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }


    public void setCadence(int newValue) {
        cadence = newValue;
    }

    public void setGear(int newValue) {
        gear = newValue;
    }

    public void applyBrake(int decrement) {
        speed -= decrement;
    }

    public void speedUp(int increment) {
        speed += increment;
    }

    public void printDescription() {
    System.out.println("\nBike is " + "in gear " + this.gear
        + " with a cadence of " + this.cadence +
        " and travelling at a speed of " + this.speed + ". ");
    }
}
}
4

2 回答 2

3

您将方法放在方法中,实际上您的 main 方法包含了 Bicycle 类的所有代码——不要这样做。你的 main 方法应该是它自己的独立方法,不应该持有其他方法,应该创建一个 Bicycle 实例。在这个实例上调用方法,就是这样。

public class Bicycle {
        public int cadence;
        public int gear;
        public int speed;

    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }


    public void setCadence(int newValue) {
        cadence = newValue;
    }

    public void setGear(int newValue) {
        gear = newValue;
    }

    public void applyBrake(int decrement) {
        speed -= decrement;
    }

    public void speedUp(int increment) {
        speed += increment;
    }

    public void printDescription() {
    System.out.println("\nBike is " + "in gear " + this.gear
        + " with a cadence of " + this.cadence +
        " and travelling at a speed of " + this.speed + ". ");
    }

    public static void main(String[] args) {
      Bicycle bicycle = new Bicycle(20, 10, 2);
      System.out.println(bicycle);
      // ... etc
    }
}

下次,请从一开始就向我们展示导致问题的实际代码以及您的错误消息。这样你会得到更好的帮助,我们都会少一点沮丧。

于 2013-04-23T19:25:41.107 回答
1

接受以前的答案并重新开始,尝试分解不同的方法并调试每个方法,而不是洗掉错误并折腾你的手。确保每个都在您编码时编译,以便您知道问题从哪里开始。

于 2013-04-23T22:27:07.487 回答