【问题标题】:How can you declare a class field that can be an object of one of a superclass's subclasses如何声明一个可以成为超类子类之一的对象的类字段
【发布时间】:2020-11-11 13:41:33
【问题描述】:

例如:

public class Building{
   private int x;
   private int y;
   private int z;
}
public class Office extends Building{
   public void fx()
   public void fy()
   public Office(int x, int y, int z){
      x = x;
      y = y;
      z = z;
   }
}
public class School extends Building{
   public void fa()
   public void fb()
   public School(int x, int y, int z){
      x = x;
      y = y;
      z = z;
   }
}

那么我应该在下面代码中的空白处放置什么来引用Building的子类? 换句话说,我应该在其中放置什么,以便 building 具有 Office 或 Building 的数据类型,其数据类型可以由构造函数确定?

public class foo{
   private int dummy;
   private ____ building;

   public foo(int nd, ____ nb){
      dummy = nd;
      building = nb;
   }
}
public class mainF{
   public static void main(String[] args){
      foo object1 = new foo(1, new Office(1,2,3)); 
      foo obhect2 = new foo(1, new School(1,2,4)); 
   }
}

【问题讨论】:

  • 我是Building
  • 如果这个领域叫建筑,你怎么看?
  • 您是否看过泛型,例如Foo<T extends Building>private T buildingFoo(int nd, T nb)? - 不要忘记在main() 中的调用中添加泛型类型(如果你问如何做到这一点:阅读一些关于泛型的教程)。

标签: java oop subclass superclass


【解决方案1】:

如果 Office 和 School 是 Building 的实现,那么您可以像处理 Building 对象一样处理它们。

也许你的问题没有完全暴露?

【讨论】:

    猜你喜欢
    • 2016-11-28
    • 2021-11-25
    • 2017-05-12
    • 2016-01-16
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    相关资源
    最近更新 更多