对于入门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