公共课的非法表达开始

时间:2014-12-16 19:40:11

标签: java

我正在尝试编写一个利用java的Abstract类功能的程序。我得到了一个非正式的表达方式"第63行的错误,它声明了公共类AbstractCar。任何人都可以解释为什么我会收到此错误以及如何纠正错误。提前谢谢

public class AbstractCar {
  public static final void main(String args[]) {

    abstract class Vehicle {
      //subclasses will inherit an attribute
      int maxSpeed;
      //subclasses must implement this method 
      //(otherwise they have to be declared as abstract classes)
      abstract void showMaxSpeed();
      //subclass will have this method (through inheritance) as is (default implementation)
      //or they may implement their own implementation (override a method)
      int getWheelsNumber() {
        return 4;
      }
    }

    /**Car IS-A Vehicle*/
    class Car extends Vehicle {
      public Car() {
        maxSpeed = 180;
      }

      public void showMaxSpeed() {
          System.out.println("Car max speed: " + maxSpeed + " km/h");
        }
        //Car class will inherit getWheelsNumber() method from the parent class
        //there is no need to override this method because default implementation
        //is appropriate for Car class - 4 wheels
    }

    /**Bus IS-A Vehicle*/
    class Bus extends Vehicle {
      public Bus() {
        maxSpeed = 100;
      }

      public void showMaxSpeed() {
          System.out.println("Bus max speed: " + maxSpeed + " km/h");
        }
        //Bus class will override this method because the default implementation
        //is not appropriate for Bus class
      public int getWheelsNumber() {
        return 6;
      }
    }

    /**Truck IS-A Vehicle*/
    class Truck extends Vehicle {
      public Truck() {
        maxSpeed = 80;
      }

      public void showMaxSpeed() {
          System.out.println("Truck max speed: " + maxSpeed + " km/h");
        }
        //Truck class will override this method because the default implementation
        //is not appropriate for Bus class
      public int getWheelsNumber() {
        return 10;
      }
    }

    public class AbstractCar {

      public static void main(String[] args) {
        Vehicle car = new Car();
        Vehicle bus = new Bus();
        Vehicle truck = new Truck();
        car.showMaxSpeed();
        bus.showMaxSpeed();
        truck.showMaxSpeed();
        System.out.println("Wheels number-car:" + car.getWheelsNumber() +
          ", bus:" + bus.getWheelsNumber() + ", truck:" + truck.getWheelsNumber());
      }
    }

  }
}

1 个答案:

答案 0 :(得分:5)

你不能在方法中声明一个类(除非它是一个匿名类)。

public class AbstractCar {
 public static final void main(String args[]) {

abstract class Vehicle { // move this class definition outside your main method