0

Hi I have a class Property and 2 subclasses Shop and Apartment.

In another class I have an arraylist of properties with a mixture of shops and apartments. I have the code:

for(Property prop: properties){
  if(prop.getClass().equals(Shop.class))
       prop.setShopDetails(detail);
  else
       prop.setAppDetails(detail)
}

How can I access the method setShopDetails() inside the shop class?

3 Answers 3

6

You need to cast prop to a Shop:

for(Property prop: properties){
  if(prop.getClass().equals(Shop.class))
       ((Shop) prop).setShopDetails(detail);
  else
       ((Apartment) prop).setAppDetails(detail)
  }
}

A better approach, however, would be to define an abstract method setDetails in the Property class and implement it differently in each subclass. You might also want to use prop instanceof Shop instead of prop.getClass().equals(Shop.class).

Sign up to request clarification or add additional context in comments.

Comments

2

First of all, consider the case where prop is a subclass of Shop. Your if condition would return false! This is the perfect time to use the instanceof operator.

In order to access those methods, you need to cast your object to the correct subclass:

if(prop instanceof Shop) {
    Shop s = (Shop) prop;
    s.setShopDetails(details);
} else {
    // you get the idea
}

However, this kind of defeats the purpose of polymorphism. Why not create a setDetails method in Property and allow subclasses to handle it how they will?

Comments

0

First, the fact that you have to call getClass() in this situation usually indicates faulty design. You probably want to have a single abstract setDetails method that is overridden by the subclasses.

The language feature you are looking for is "casting". Before calling a subclass method, you want to cast your Property like so:

((Shop)prop).getShopDetails(detail);

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.