有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

公共类的表达式的java非法开始

我正试图编写一个利用java抽象类特性的程序。我在第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) 个答案

  1. # 1 楼答案

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

    public class AbstractCar {
     public static final void main(String args[]) {
    
    abstract class Vehicle { // move this class definition outside your main method