继承相同类的所有对象的方法?

huangapple go评论84阅读模式
英文:

Method for all objects that extend the same class?

问题

假设我有3个类,它们都扩展自相同的类...

public class Foo {
     private String name;
     ...
}
public class FooExtend1 extends Foo {
     ...
}
public class FooExtend2 extends Foo {
     ...
}
public class FooExtend3 extends Foo {
     ...
}

然后我创建一个工具函数来更改从Foo继承的属性...

public void changeName(??? param1) {
     param1.setName("");
}

我希望param1是扩展自Foo类的所有对象。

我是否需要重载该方法,还是有其他方法?

英文:

Let say I have 3 classes that all extend the same class...

public class Foo {
     private String name;
     ...
}
public class FooExtend1 extends Foo {
     ...
}
public class FooExtend2 extends Foo {
     ...
}
public class FooExtend3 extends Foo {
     ...
}

then I create a util function that changes the property that implements from Foo...

public void changeName(??? param1) {
     param1.setName("");
}

and I want param1 to be all objects that extends from the Foo class.

Would I have to overload the method or is there another way?

答案1

得分: 3

我们不需要覆盖该方法,因为类型之间的继承关系赋予了从子类型到超类型的隐式扩宽转换的能力(参见JLS,§5.1.5)。因此,我们可以将方法重写为:

public void changeName(Foo param1) {
     param1.setName("");
}

Ideone演示(我随意设置了实用方法中的name"foo",以便我们可以看到方法在演示输出中的效果)

这按预期工作,前提是Foo有一个方法public String setName(String)


备注:我建议将方法changeName(...)重命名为更具表达性的名称,例如setEmptyName(...)resetNameToDefault(...)

英文:

We do not need to override the method since the inheritance-relationship between the types grants the capabilites of implicit widening conversion from sub- to supertype (see JLS, §5.1.5). Thus, we can rewrite the method to

public void changeName(Foo param1) {
     param1.setName("");
}

<kbd>Ideone demo</kbd> (I took the liberty and set the name in the utility method to &quot;foo&quot; so we can see that the method works in the demo output)

This works as expected, given that Foo has a method public String setName(String).


A remark: I would suggest renaming method changeName(...) to something more expressive, e.g. setEmptyName(...) or resetNameToDefault(...).

答案2

得分: 0

你在父类中定义的方法对所有子类都是可访问的:

public void changeName(String param1) {
     this.name = param1;
}

如果你想在某个类外部拥有方法:

public void changeName(Foo foo, String newName) {
     foo.setName(newName);
}

你可以传递任何Foo的子类进去。

英文:

Your method defined in parent is accessible for all its children:

public void changeName(String param1) {
     this.name = param1;
}

If you want to have method in some class outside:

public void changeName(Foo foo, String newName) {
     foo.setName(newName);
}

and you can pass any Foo descendant there.

huangapple
  • 本文由 发表于 2020年9月24日 22:03:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64048179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定