Search code examples
javasubclasssuperclass

How to choose a sub-class in Java


i am making a program which has a super class called Building, this class has one variable which is the address of the building. Then i have two sub-classes one is called Apartment the other one is called Restaurant. I defined those classes like this:

public class Apartment extends Building;
public class Restaurant extends Building;

Now i have a function public void register(Building build); and i want to know how can i choose a sub-class to store the information by receiving the super class only. E.g:

0.Apartment
1.Restaurant
Which building do you have?

Now depending on user's answer i will ask

How many rooms, bathrooms, etc.

My starter point is Building class now i need to choose, if the user answered 0 i will be using Apartment sub-class, otherwise i will use Restaurant sub-class. How can i do this? Let me know if there is a better way to do this. Thank you.


Solution

  • You could go with method overloading: Make register methods with your sub-classes as arguments. Do the sub-class specific work in those methods and then call a private register(Building building) method to do the common work.