如何实现一个抽象的方法class? (Java)

How to implement methods of an abstract class? (Java)

我正在尝试使用实现接口的抽象 class 中的方法。当我调用一个方法时,我总是收到一个空指针异常,我不确定为什么。有任何想法吗?谢谢。

package start;
public class Automobile extends Vehicle {     // code with main method
public static void main(String[] args) {
         Vehicle[] automobiles = new Vehicle[3];
         automobiles[0].setVehicleName("Corvette");
    }
}

////////////////////////////////////////// ///////////////////////////

package start;

public abstract class Vehicle implements Movable {

    String name = "Unidentified"; // variables for vehicles
    String manufacturer = "Factory";
    String car = "Unknown";
    int yearOfManufacture = 0000;
    int horsepower = 0;
    static int instances = 0;

    int passengers = 0; // variables for methods below
    int speed = 0;

    public int getNoPassengers() { // returns how many passengers there are
        instances = instances + 1;
        return passengers;
    }

    public void setNoPassengers(int noPassengers) { // sets the number of passengers
        instances = instances + 1;
        passengers = noPassengers;
    }

    public int getTopSpeed() { // returns how fast a movable vehicle is
        instances = instances + 1;
        return speed;
    }

    public void setTopSpeed(int topSpeed) { // changes the speed of a movable vehicle
        instances = instances + 1;
        speed = topSpeed;
    }

    public void setVehicleName(String title) { // changes the name of a vehicle
        instances = instances + 1;
        name = title;
    }

    public String getVehicleName(String car){
        return car;
    }

    public void setManufacturer(String creator) { // changes the manufacturer
        instances = instances + 1;
        manufacturer = creator;
    }

    public String getManufacturer(String type){
        return type;
    }
}

////////////////////////////////////////// /

package start;

interface Movable {      // interface

    int getNoPassengers(); // returns how many passengers there are

    void setNoPassengers(int noPassangers); // sets the number of passengers

    int getTopSpeed(); // returns how fast a movable vehicle is

    void setTopSpeed(int topSpeed); // changes the speed of a movable vehicle
}

您在邮件中的代码如下:

Vehicle[] automobiles = new Vehicle[3];
automobiles[0].setVehicleName("Corvette");

此处您刚刚分配了数组,但其中的元素仍然为空(因此在对空对象调用 setter 时出现空指针异常)并且需要初始化,如:

automobiles[0] = new ....;
//then access method from within automobiles[0]

问题是您只在以下几行中创建了车辆数组 -

Vehicle[] automobiles = new Vehicle[3];

您仍然需要使用 new Vehicle(或 new Automobile ,因为 Vehicle 是抽象的 class 并且无法实例化)将变量初始化为对象,然后才能访问它们。

例子-

Vehicle[] automobiles = new Vehicle[3];
automobiles[0] = new Automobile();
automobiles[0].setVehicleName("Corvette");