java - 在实现两个相似类的方法时是否可以避免重复代码?

标签 java overloading

我有两个类:FishPlant。它们不继承任何类。

但是它们都有一个名为 isAlive() 的方法,它具有相同的实现细节。现在我有一份鱼 list 和另一份狗 list ,我需要删除死鱼和死狗。我希望我的方法具有相同的名称,但如果不向方法签名添加附加字段,这是不可能的。我是否可能不需要编写与最后一 block 代码相同的额外代码块?

下面是代码。对于Model类,FishPlant是两个数据成员,它们是FishPlant的ArrayList 对象。

有什么方法可以让我只编写一个名为 count 的方法,并且不需要向方法签名添加其他字段或修改我的返回类型?

public class Fish{
    public boolean isAlive(){
        if(this.size > 0){
            return true;
        }
        return false;
    }
}
public class Plant{
    public boolean isAlive(){
        if(this.size > 0){
            return true;
        }
        return false;
    }
}

public class Model{
    private int countDeadFish() {
        int totalCount = 0;
        for(Fish aFish : this.fish) {
            if(aFish.isAlive() == false) {
                totalCount += 1;
            }
        }
        return totalCount;
    }

    private int countDeadPlants() {
        int totalCount = 0;
        for(Plant plant : this.plants) {
            if(plant.isAlive() == false) {
                totalCount += 1;
            }
        }
        return totalCount;
    }
}

最佳答案

如果不想使用继承,那么可以使用通用方法:

public class AliveChecker {

    public static boolean isAlive(int size) {
        return size > 0;
    }

}

public class Plant{
    public boolean isAlive(){
        return AliveChecker.isAlive(this.size);
    }
}

public class Fish{
    public boolean isAlive(){
        return AliveChecker.isAlive(this.size);
    }
}

关于java - 在实现两个相似类的方法时是否可以避免重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50197464/

相关文章:

java - bindFactory 不注入(inject)字段

java - 使用 Android 异步 HTTP 时没有得到响应(来自 loopj)

java - 如何在java中将excel文件格式xls和xlsx相互转换

c++ - 重载==递归比较两个链表

c# - 使用类层次结构重载 - 大多数派生未使用

java - Google Drive API v3 中等效的 File.setTitle 方法

java - 解析文件并将各行分割成二维数组

java - 使用泛型重构多个重载方法

c++ - C++ 中继承的重载规则

c++ - 如何在命名空间中使用 += 函数