【发布时间】:2023-03-17 22:51:01
【问题描述】:
我刚开始学习 java,我得到了一个关于构造函数和实例的非常简单的任务。出于某种原因,我的实例在创建时没有被设置,只有在我调用 set 方法时才设置。你能帮帮我吗?我已经被困了一段时间了,无处可去。
package hka437documents;
/**
*
* @author Henry
*/
public class Hka437Documents{
public static class Documents {
/**
* @param args the command line arguments
*/
private String title;
private String author;
private String body;
private int version;
public Documents(String title, String author){
version = 0;
}
public Documents(String title, String author, String body){
version = 1;
}
public void setTitle(String title){
this.title = title;
version++;
}
public void setAuthor(String author){
this.author = author;
}
public void setBody(String body){
this.body = body;
version++;
}
public String getTitle(){
return title;
}
public String getAuthor(){
return author;
}
public String getBody(){
return body;
}
public int getVersion(){
return version;
}
}
public static void main(String[] args) {
Documents document1 = new Documents("Another Life", "Sally Smith");
document1.setBody("The grass is always greener on the other side.");
Documents document2 = new Documents("Final Word", "Karen Jones", "We should plan for the worst and hope for the best.");
document2.setTitle("Final Words");
System.out.println("document1:");
System.out.println("Title: "+ document1.getTitle());
System.out.println("Author: "+ document1.getAuthor());
System.out.println("Body: "+ document1.getBody());
System.out.println("Version: "+ document1.getVersion());
System.out.println("\ndocument2:");
System.out.println("Title: "+ document2.getTitle());
System.out.println("Author: "+ document2.getAuthor());
System.out.println("Body: "+ document2.getBody());
System.out.println("Version: "+ document2.getVersion());
}
}
当我运行程序时,除了 document1+2 版本、document1 正文和 document2 标题之外,所有这些语句的打印语句都为 null。这些是使用 set 方法设置变量的那些。
【问题讨论】:
-
你对你的构造函数参数做了nothing。它们不会通过魔法改变对象的状态——您需要将它们的值分配给对象的状态字段。
-
反对者愿意发表评论吗?是的,这是一个初学者问题,但它包含必需的元素(代码,对什么不起作用的解释)。在某些时候我们都是新手,至少这个新手知道如何提出问题。
标签: java constructor