3gordd
3gordd

Reputation: 35

How can you declare a class field that can be an object of one of a superclass's subclasses

For example:

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;
   }
}

So what should I place in the blank in the code below to refer to the subclasses of Building? In other words, what should I place there such that building has a datatype that is Office or Building, whose datatype could be determined by a constructor?

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)); 
   }
}

Upvotes: 0

Views: 199

Answers (1)

Andrea Coluzzi
Andrea Coluzzi

Reputation: 39

If Office and School are implementations of Building, then you could handle them like a Building object.

Maybe your question is not completely exposed?

Upvotes: 1

Related Questions