英文:
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 "foo"
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论