我试图了解一些继承概念。
请考虑以下理论代码。 在下面的代码中,方法GetName将返回Fruit的名称。 我希望它能归还草莓或苹果公司的名字。
与此问题相反:Java Inheritance... Confused子对象的类型不同,因此我建议的解决方案并不适用。
如果有解决方案,请告诉我吗?public class Parent{
private Fruit aFruit = new Fruit(); // Fruit has a method getName
public void commonProcess(){
//Do some things Common to Child 1 and 2
...
//
System.out.println("I am a:"+ aFruit.getName());
//Do more things Common to Child 1 and 2
...
//
}
}
public class Child1 extends Parent{
private Strawberry aStrawb = new Strawberry(); // Strawberry extends Fruit
public void someMethod1(){
// Do something specific to Child2
...
//
System.out.println(commonProcess());
}
}
public class Child2 extends Parent{
private Apple anApple = new Apple(); // Apple extends Fruit
public void someMethod2(){
// Do something specific to Child2
...
//
System.out.println(commonProcess());
}
}
当Child 1和Child 2调用commonProcess()时,它们将调用Fruit.getName方法。 我想要的是,根据调用它的人调用与Child类中的fruit相关联的方法的父方法。 我能看到的唯一方法是在Child1和Child2中复制commonProcess,然后调用本地Fruit的getName,但由于commonProcess方法做了很多其他事情,复制大量代码似乎效率低下。