提问者:小点点

多态+重载--如何使子类的多态/重载方法得到调用?


我有一个形状和方块类:

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 Call”是输出。

有没有一种方法可以通过纯多态获得“Child doSomething for SQUARE Call”输出,而不在父类中定义doSomething(SQUARE a)并在子类中使用@Override?

不用说,我正试图避免任何IF/ELSE检查与实例的操作符和额外的铸型。


共1个答案

匿名用户

下面工作正常

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");
    }
}