對於入門Java,我創建了一個Door類和一個DoorTester類。基本上,我們正在試驗實例變量並創建公共方法。我所做的大門類,如下所示,但我DoorTester返回 「空」 時,它看起來.getState方法返回null [簡單]
Door.java
public class Door {
// Create instance variables of type String
private String name;
private String state;
// Declare method 'open' and 'close'
public void open() {
state = "open";
}
public void close() {
state = "closed";
}
// Add a constructor for the Door class
public Door(String name, String state) {
}
// Create an accessor of 'state'
public String getState() {
return name;
}
// Set the state
public void setState(String newState) {
state = newState;
}
}
DoorTester.java
public class DoorTester {
public static void main(String[] args) {
Door frontDoor = new Door("Front", "open");
System.out.println("The front door is " + frontDoor.getState());
System.out.println("Expected: open");
Door backDoor = new Door("Back", "closed");
System.out.println("Expected: closed");
// Use the mutator to change the state variable
backDoor.setState("open");
System.out.println("The back door is " + backDoor.getState());
System.out.println("Expected: open");
// Add code to test the setName mutator here
}
}
你沒有在你的構造函數中設置私有變量..... – Sebas 2014-09-26 04:44:03
你從來沒有在你的構造函數中分配你的變量。 – theGreenCabbage 2014-09-26 05:33:56