方法返回null [simple]

时间:2014-09-26 04:41:22

标签: java null encapsulation instance-variables

对于介绍性Java,我创建了Door类和DoorTester类。基本上,我们正在尝试实例变量和创建公共方法。我按照以下方式开门,但我的DoorTester返回" null"当它寻找.getState

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 
  }

}

3 个答案:

答案 0 :(得分:1)

您必须修改Door类的构造函数,如

public Door(String name, String state) {
this.name=name;
this.state=state;
}

实际上namestate未初始化。 另请参阅此 What is the meaning of "this" in 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) {
 this.name=name;
 this.state=state;
}

// Create an accessor of 'state'
public String getState() {
    return state;            //<<<<<<<----------also make an Edit here 
}

// Set the state
public void setState(String newState) {
    state = newState;
}
}

答案 1 :(得分:0)

您的getState()方法无法返回state,它会返回name

// Create an accessor of 'state'
public String getState() {
    return name; // <-- Simply change this
}

此外,您的构造函数不会设置字段。你需要做这样的事情:

// Add a constructor for the Door class
public Door(String name, String state) {
    this.name = name;
    this.state = state;
}

答案 2 :(得分:0)

您的Door班级中存在问题

public class Door {
private String name;
private String state;

public void open() {
    state = "open";
}

public void close() {
    state = "closed";
}

public Door(String name, String state) { // argument passed here need to set
// set like
  this.name=name;
  this.state=state;
}

public String getState() {
    return name;
}

public void setState(String state) { 
    state = state; // you need to use this.state=state
 }
}

Java

this关键字的重要性