返回类型的方法 [英] return type of method

查看:72
本文介绍了返回类型的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class A
{
  public static void main(String []args)
  {
    X(1);
  }
  public ????? X(int i)
  {
    if(i==0)
      return new B();
    else
      return new C();
  }
}
public class B
{
}
public class C
{
}





什么应该是方法X的返回类型代替?????



what should be the return type of method X in place of ?????

推荐答案

要使代码编译,您可以将X的返回类型声明为Object。这将起作用,因为一切都是一个对象。然而,这是糟糕的设计!



您的工厂(方法X)正在创建两种类型的对象,因为它们有一些共同点。如果它们根本不相关,那么为什么需要用相同的方法创建它们?



在OOP中,你通过基类或接口表达这种共性并让它们让工厂返回普通类型。

To make the code compile you can declare X's return type as Object. This will work as everything is an object. However it is bad design!

You factory (method X) is creating objects of both types because they have something in common. If they are not related at all then why they need to be created in the same method?

In OOP you express this commonality by a base class or an interface and let the factory return then common type.
public abstract class Account {}

public class SavingsAccount extends Account {}

public class TransactionAccount extends Account {}

public Account Create(int type)
{
    if(type == 0) 
        return new SavingsAccount();
    else
        return new TransactionAccount(); 
}


这篇关于返回类型的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆