【问题标题】:Polymorphism + Overloading - How to make a child class' polymorphic/overloaded method get called?多态性 + 重载 - 如何调用子类的多态/重载方法?
【发布时间】:2020-07-02 13:48:43
【问题描述】:

我有一个 Shape 和 Square 类:

public class Shape {..}
public class Square extends Shape {...}

我有一个父子类,它们具有处理形状/正方形的方法:

public class Parent(){
    public void doSomething(Shape a){
        print("Parent doSomething called");
    }
}

public class Child extends Parent(){

    @Override
    public doSomething(Shape a){
        print("Child doSomething for SHAPE called");
    }


    public doSomething(Square a){
        print("Child doSomething for SQUARE called");
    }
}

现在,当我执行此操作时:

Shape square = new Square();

Parent parent = new Child();

parent.doSomething(square);

正如预期的那样,“Child doSomething for SHAPE called”是输出。

有没有办法通过纯多态性来获得“SQUARE 的子 doSomething 调用”输出,而无需在 Parent 类中定义 doSomething(Square a) 并使用@Override 在孩子中?

不用说,我试图避免使用运算符实例和额外的铸件进行任何 if/else 检查。

【问题讨论】:

  • “纯”解决方案是双重分派,java 没有实现。您可以使用访问者模式作为解决方法。
  • @NathanHughes 有没有实现这个的语言? C# 实现了吗?

标签: java oop inheritance polymorphism overloading


【解决方案1】:

您要做的是让每个形状负责打印/返回消息本身,即:

class Shape {
    public String doSomething(){
        return "doSomething for SHAPE called";
    }
}

class Square extends Shape {
    @Override
    public String doSomething(){
        return "doSomething for SQUARE called";
    }
}

这是你的父子类:

class Parent{
public void doSomething(Shape a){
    System.out.println("Parent doSomething called");
        }
}

class Child extends Parent{

@Override
public void doSomething(Shape a){
            System.out.println("Child "+a.doSomething());
        }
}

执行:

Shape square = new Square();
Parent parent = new Child();
parent.doSomething(square);

希望这是有道理的。

【讨论】:

    【解决方案2】:

    下面的工作正常

    public class PloyM {
        public static void main(String[] args) {
            Child c = new Child();
            c.doSomething(new Shape());
            c.doSomething(new Square());
        }
    }
    
    class Shape { }
    class Square extends Shape {}
    
    class Parent {
        public void doSomething(Shape a){
            System.out.println("Parent doSomething called");
        }
    }
    
    class Child extends Parent {
        @Override
        public void doSomething(Shape a){
            System.out.println("Child doSomething for SHAPE called");
        }
    
        public void doSomething(Square a){
            System.out.println("Child doSomething for SQUARE called");
        }
    }
    

    【讨论】:

    • 我希望使用父类而不是这个:Child c = new Child();
    • sry,错过了那部分 - 如果你输入它作为 Parent - 它不能知道另一个 doSomething(Square) - 你必须参考 Child 来查看方法 doSomething(Square)
    猜你喜欢
    • 2011-06-25
    • 2011-06-22
    • 2020-09-25
    • 2017-06-06
    • 2010-11-14
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 2011-07-23
    相关资源
    最近更新 更多