0

I have a base class Building and subclasses House and School. I have declared an array of Building objects the following way. I am not sure how to assign subclasses to each array element (run time type).

Building[] House = new Building[3];
Building[] School = new School[2];
4
  • What issues are you running into? Are you getting compiler errors? Commented Mar 10, 2014 at 18:27
  • House ob = House[0]; & School obj = House[1]; Commented Mar 10, 2014 at 18:27
  • Java's convention is to use lowerCamelCase for variables and CamelCase for classes. Following these conventions will make the code easier to work with for all developers. Commented Mar 10, 2014 at 18:31
  • 1
    Is School a variable name or a class name? You're using it both different ways in the same statement. Commented Mar 10, 2014 at 18:32

2 Answers 2

2

You can use instanceof to determine the subclass

if (building instanceof House) {
    House[0] = building;
}
Sign up to request clarification or add additional context in comments.

Comments

1

I'm not sure if you are asking how to check types at runtime or to populate with types at runtime. If the latter then see @Salah's answer using instanceof. In particular, why the House array is being populated with Building objects while the School array is being populated with School objects is confusing me.

To assign:

Building[] house = new House[3];
Building[] school = new School[2];

You could also populate the array with Building objects and then use type checking when you need to down the road.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.