我正在嘗試使用實現接口的抽象類中的方法。當我調用一個方法時,我總是收到一個空指針異常,我不知道爲什麼。有任何想法嗎?謝謝。如何實現抽象類的方法? (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]。這就像這樣做 - 汽車汽車; auto.setVehicleName( 「A」); – Ouney