Reputation: 153
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?
Upvotes: 0
Views: 472
Reputation: 44808
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?
Upvotes: 2
Reputation: 15018
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);
Upvotes: 0
Reputation: 234795
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)
.
Upvotes: 6