是否对施工人员有任何要求';Java中的s参数

是否对施工人员有任何要求';Java中的s参数,java,constructor,Java,Constructor,通常,构造器如下所示 private int occurence; private String content; public Word(String content,int occurence) { this.content= content; this.occurence = occurence; } 但是,我可以设置不直接指定给属性但计算属性值所需的参数吗 例如,Article类中有一个名为caloccurrence(String content)的方法,可以根据文章计算发

通常,构造器如下所示

private int occurence;
private String content;
public Word(String content,int occurence)
{
   this.content= content;
   this.occurence = occurence;
}
但是,我可以设置不直接指定给属性但计算属性值所需的参数吗

例如,Article类中有一个名为caloccurrence(String content)的方法,可以根据文章计算发生率。那么我能像这样建造这个建筑吗

public Word(String content, Article base)
{
   this.content= content;
   this.occurence = base.calOccurence(content);
}
如果caloccurrence函数属于Word类,比如caloccurrence(字符串内容、文章库),该怎么办

public Word(String content, Article base)
{
   this.content= content;
   this.occurence = this.calOccurence(content, base);
}

这看起来很奇怪,但我的队友编写的代码与上面类似。我想知道这是否合理?

因为单词的出现离不开文章,所以我认为最好在word类中省略出现字段,而只在Article类中使用它

像这样的

public class Word {
    String text;
    Article article;

    public Word(String text, Article article) {
        this.text = text;
        this.article = article;
    }

    // other code
}

public class Article
    String content;
    public Article(String content) {
        this.content = content;   
    }

    public int calOccurrence(Word word) {
        // Calculate the occurrence of word.text in this.content
    }

    // other code
}

构造函数应始终确保生成的对象已完全初始化并准备好使用。调用类中的其他方法来完成这项工作是完全可以接受的,但是您必须确保它们可以处理处于未定义状态的对象

在您的示例中,如果对
this.caloccurrence
的调用发生在设置
this.content
之前,则
this.caloccurrence
方法仍然需要工作。这就是为什么该方法不依赖
This.content
变量,而是要求您传入内容值。将
content
作为参数传递,而不是依赖于类的属性,可以确保它始终拥有所需的所有数据


现在,如果不总是需要出现的次数,将其转换为惰性属性并仅在需要时计算其值可能是更好的策略。

请注意,您的ctor代码与您的同事明显不同,因为您试图调用
文章
上的
calOccurence
,而不是正在构造的
Word
实例。同事的ctor唯一“奇怪”的地方是它没有使用实例的
content
属性,而是传入ctor参数——但这本质上并不奇怪。最终你可以将你想要的任何东西传递到构造函数中。这是合法的,尽管这个例子不是一个合理的设计,依我看:
caloccurrence
看起来像是一个潜在的昂贵操作,而
Word
看起来像是一个你想要创建许多实例的对象;每次执行
新单词
,每个单词都要扫描一次内容。