簡體   English   中英

多態性 + 重載 - 如何調用子類的多態/重載方法?

[英]Polymorphism + Overloading - How to make a child class' polymorphic/overloaded method get called?

我有一個形狀和正方形 class:

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

我有一個父子 Class 有處理形狀/正方形的方法:

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”是 output。

有沒有辦法通過純多態性獲得“稱為SQUARE的子 doSomething”output,而無需在父 class 中定義doSomething(Square a)並在子級中使用 @Override?

不用說,我試圖避免使用運算符實例和額外的鑄件進行任何 if/else 檢查。

您要做的是讓每個形狀負責打印/返回消息本身,即:

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

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

這是您的父母和孩子 class:

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

希望這是有道理的。

下面工作正常

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM