[英]How to call same method from two different classes in java
I have two classes Apple and Orange like this: 我有两个类Apple和Orange这样:
public final class Apple{
int getJuice();
}
public final class Orange{
int getJuice();
}
and I cannot change them . 我无法改变它们 。 I have third class fruitsManeger like this:
我有这样的第三类fruitsManeger :
class FruitManeger {
Apple apple;
Orange orange;
enum Fruits{
Apple,Orange
}
Fruits favorFruits;
int getJoice(){
if(favorFruits==Fruits.Apple){
apple.getJuice();
}else if(favorFruits==Fruits.Orange){
orange.getJuice();
}
}
}
My Question: what is best way to implement getJuice method in FruitManeger class?. 我的问题:在FruitManeger类中实现getJuice方法的最佳方法是什么?
as you can see if I have a lot of fruits I should add a lot of if else expiration. 你可以看到,如果我有很多水果,我应该添加很多if else expiration。
of course, I can use reflection to call methods by name but it's not a good idea when getJuice method return an object and you want to do something same with that. 当然,我可以使用反射来按名称调用方法,但是当getJuice方法返回一个对象而你想要做同样的事情时,这不是一个好主意。
is there any better way? 有没有更好的方法?
is there any better way?
有没有更好的方法?
Yes, Refactor that application into a more oop way... 是的,将该应用程序重写为更加明确的方式......
Remember: you cannot Modify Apple or Orange, but OOP allows you extending those classes for sure since they are not final... 记住:你不能修改Apple或Orange,但OOP允许你扩展这些类,因为它们不是最终的...
class CorrectApple extends Apple implement IJuiceble{
@Override
int getJuice();
}
class CorrectOrange extends Orange implement IJuiceble{
@Override
int getJuice();
}
now the 现在
interface IJuiceble{
int getJuice();
}
and finally the manager: 最后经理:
class FruitManeger {
private CorrectApple apple;
private CorrectOrange orange;
int getJoice(IJuiceble correctfruit){
return correctfruit.getJuice();
}
}
You can use switch instead of if/else. 您可以使用switch而不是if / else。
class FruitManager {
Apple apple;
Orange orange;
enum Fruits {
Apple, Orange
}
Fruits favorFruits;
int getJoice() {
switch (favorFruits) {
case Apple:
apple.getJuice();
break;
case Orange:
orange.getJuice();
break;
default:
System.err.println("Fruit not found. " + favorFruits);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.