[英]How to implement methods of an abstract class? (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
}
問題是您只在以下幾行中創建了車輛數組 -
Vehicle[] automobiles = new Vehicle[3];
在訪問變量之前,您仍然需要使用 new Vehicle (或 new Automobile ,因為 Vehicle 是一個抽象類並且無法實例化)將變量初始化為對象。
例子 -
Vehicle[] automobiles = new Vehicle[3];
automobiles[0] = new Automobile();
automobiles[0].setVehicleName("Corvette");
您在郵件中的代碼如下:
Vehicle[] automobiles = new Vehicle[3];
automobiles[0].setVehicleName("Corvette");
在這里,您剛剛分配了數組,但其中的元素仍然為空(因此在空對象上調用 setter 時出現空指針異常)並且需要初始化,例如:
automobiles[0] = new ....;
//then access method from within automobiles[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.