子类调用父保护方法,期望返回受保护的覆盖属性。 但是要返回父母的财产。
//父类:
package tz import java.util.List; class AbstractController { protected List keywordFilter = [] protected String methodKey(){ return "\t[method]parent,$keywordFilter,"+keywordFilter.toString() } def closureKey(){ return "\t[closure]parent,$keywordFilter,"+keywordFilter.toString() } }//子类:
package tz import java.util.List; class SubController extends AbstractController{ protected List keywordFilter = ['a'] public SubController(){ } public void test(){ println "subCall:"+methodKey()+closureKey() } def test2 = { println "c,$keywordFilter,"+methodKey()+closureKey() } public static void main(String[] args) { def s = new SubController() s.test() s.test2() } }//输出:
subCall:[method]parent,[],[] [closure]parent,[],[] c,[a], [method]parent,[],[] [closure]parent,[],[]subclass call parent protected method which expect return a protected override property. but return the parent's property.
//ParentClass:
package tz import java.util.List; class AbstractController { protected List keywordFilter = [] protected String methodKey(){ return "\t[method]parent,$keywordFilter,"+keywordFilter.toString() } def closureKey(){ return "\t[closure]parent,$keywordFilter,"+keywordFilter.toString() } }//SubClass:
package tz import java.util.List; class SubController extends AbstractController{ protected List keywordFilter = ['a'] public SubController(){ } public void test(){ println "subCall:"+methodKey()+closureKey() } def test2 = { println "c,$keywordFilter,"+methodKey()+closureKey() } public static void main(String[] args) { def s = new SubController() s.test() s.test2() } }//Output:
subCall:[method]parent,[],[] [closure]parent,[],[] c,[a], [method]parent,[],[] [closure]parent,[],[]最满意答案
在Java和Groovy中,子类中的字段不会被覆盖。 基类版本仅由子类版本隐藏。 实际上,您在类中获得了两个具有相同名称的字段。 基类方法将会看到基类字段,并且子类方法将会看到子类字段。
解决方案通常是将字段包装在getter方法中。 在groovy:
class AbstractController { protected List getKeywordFilter() { [] } ... } class SubController extends AbstractController { protected List getKeywordFilter() { ['a'] } ... }遵循groovy属性约定,您仍然可以将其引用为"$keywordFilter" ,它将自动调用getter。
In Java and Groovy, fields are not overriden in subclasses. The base class version is just hidden by the subclass version. You actually get two fields in the class, with the same name. The base class methods will see the base class field and subclass methods will see the subclass field.
The solution is usually to just wrap the field in a getter method. In groovy:
class AbstractController { protected List getKeywordFilter() { [] } ... } class SubController extends AbstractController { protected List getKeywordFilter() { ['a'] } ... }Following the groovy property conventions, you can still reference it as "$keywordFilter" which will automatically call the getter.
更多推荐
发布评论