如果您收到“缺少返回语句”,您将收到编译时错误而不是运行时错误。
您收到的编译时错误表明您的方法之一需要返回语句,但该方法没有。要么返回预期的值,要么将方法签名更改为 void,这样它就不需要返回值。
下面是一个如何编写多个相互交互的对象的示例:
Q19597109.java
/**
* http://stackoverflow.com/questions/19597109/problems-compiling-classes-in-chapter-two-classes-and-objects-of-head-first-jav
*/
public class Q19597109 {
public static void main(String... args) {
Person person = new Person();
person.setName("Bob");
Greeter greeter = new Greeter(person);
greeter.sayHello();
}
}
人.java
/**
* http://stackoverflow.com/questions/19597109/problems-compiling-classes-in-chapter-two-classes-and-objects-of-head-first-jav
*/
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
Greeter.java
/**
* http://stackoverflow.com/questions/19597109/problems-compiling-classes-in-chapter-two-classes-and-objects-of-head-first-jav
*/
public class Greeter {
private final Person person;
public Greeter(Person person) {
this.person = person;
}
public void sayHello() {
System.out.println("Hello " + person);
}
}
如果这些文件中的每一个都在同一个目录中,那么您可以这样做:
javac *.java
java Q19597109
输出是:
Hello Bob