您如何声明一个 class 字段,该字段可以是 superclass 的 subclasses 之一的对象
How can you declare a class field that can be an object of one of a superclass's subclasses
例如:
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的子类呢?
换句话说,我应该在那里放置什么,使建筑物的数据类型为 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));
}
}
如果 Office 和 School 是 Building 的实现,那么您可以像处理 Building 对象一样处理它们。
可能你的问题没有完全暴露?
例如:
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的子类呢? 换句话说,我应该在那里放置什么,使建筑物的数据类型为 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));
}
}
如果 Office 和 School 是 Building 的实现,那么您可以像处理 Building 对象一样处理它们。
可能你的问题没有完全暴露?