Inheritance 这是一个bug还是Groovy中抽象类的设计?
我在Groovy中有这段代码,这是一个bug还是设计的:Inheritance 这是一个bug还是Groovy中抽象类的设计?,inheritance,groovy,abstract-class,Inheritance,Groovy,Abstract Class,我在Groovy中有这段代码,这是一个bug还是设计的: abstract class One { String content String description String returnContent(){ return content } } class Two extends One { String getContent() { content ?: description } } Two two
abstract class One {
String content
String description
String returnContent(){
return content
}
}
class Two extends One {
String getContent() {
content ?: description
}
}
Two two = new Two(description:"this is my description")
assert two.returnContent() == "this is my description"
我希望assert能够通过,但实际上不能通过,因此,调用content时似乎没有调用实例的getContent()方法。规范说明:
属性通过名称访问,并将调用getter或setter
透明,除非代码位于定义
财产。。。值得注意的是,这种访问
直接备份字段是为了防止堆栈溢出
在定义
财产
所以returnContent直接访问该字段,它不调用getContent()。这不是一个bug,它是这样设计的。不过这并不奇怪,因为您引用的是拥有该成员的抽象类中的成员。没有实例,也没有自动生成getContent。Bug?不,这是你的密码。假设你就是问题所在;第一,最后,永远。它为什么要调用getContent()?您的代码调用returnContent()。这甚至可以编译吗?可能的重复只是一个例子。我只是想知道为什么在访问content字段(在Groovy中,它通常与调用getter相同)时,抽象类实际上不是这样工作的@达菲莫,我可以多次成为问题的焦点,但这次不是。@FranGarcía提供一个例子来说明一个“问题”。如果你运行我添加到帖子中的例子,它将失败,我认为它不应该失败。