2015-06-21 104 views
-1

我正在嘗試使用實現接口的抽象類中的方法。當我調用一個方法時,我總是收到一個空指針異常,我不知道爲什麼。有任何想法嗎?謝謝。如何實現抽象類的方法? (Java)

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 
} 
+0

請使用它之前分配一個新對象到汽車[0]。這就像這樣做 - 汽車汽車; auto.setVehicleName( 「A」); – Ouney

回答

2

的問題是,你只創建了下面幾行車輛的陣列 -

Vehicle[] automobiles = new Vehicle[3]; 

您仍然需要通過新車初始化變量對象(或新汽車,因爲汽車是一個抽象類,不能被實例化),它們可以被訪問之前。

實施例 -

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

謝謝!對不起,這個愚蠢的問題。 – Equinoxinator

+0

歡迎,其確定,每個人都犯錯誤,重要的是向他們學習。 –

1

你的郵件代碼如下:

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

在這裏,您剛剛分配的數組,但元素中它仍然是空(和調用空對象的設置方法時,因此空指針異常),需要初始化以及類似:

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