如何实现抽象类的方法? (JAVA)

时间:2015-06-21 06:24:23

标签: java inheritance polymorphism

我正在尝试使用实现接口的抽象类中的方法。当我调用一个方法时,我一直得到一个空指针异常,我不知道为什么。有任何想法吗?感谢。

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;
    }
}

////////////////////////////////////////////// < / p>

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
}

2 个答案:

答案 0 :(得分:2)

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

Vehicle[] automobiles = new Vehicle[3];

在使用新的Vehicle(或新的Automobile,因为Vehicle是一个抽象类,无法实例化)之前,您仍然需要将变量初始化为对象,然后才能访问它们。

示例 -

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

答案 1 :(得分:1)

您的邮件代码如下:

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

这里你只是分配了数组但是其中的元素仍然是null(因此在调用null对象上的setter时因为空指针异常)并且需要初始化,如:

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