0

My question is, how, or if its possible, to know the dynamic type of an object in the compilator. I have this data

public abstract class accommodation;
public class Hotel extends accomodation;
public class Cabin extends accomodation;
accomodation [] array=  new accomodation[x];

My actual problem is, can i get an array with only hotels from this?

Miruuu
  • 17
  • 4
  • Possible duplicate of [Difference between Dynamic and Static type assignments in Java](https://stackoverflow.com/questions/20504714/difference-between-dynamic-and-static-type-assignments-in-java) – vinS Dec 20 '17 at 04:07
  • 2
    You can use `if (a instanceof Hotel)` (on each element) to filter the array. – Thilo Dec 20 '17 at 04:08
  • 6
    I would say that your design may have a problem if you really think you have this need. Most of the time, it is preferable to code to an interface, and deal with general accommodation objects rather than a specific subclass. – Tim Biegeleisen Dec 20 '17 at 04:08

2 Answers2

2

One way is to use filter and map to first filter out all the objects that are Hotels, and cast to Hotel.

Arrays.stream(array)
    .filter(x -> x instanceof Hotel)
    .map(x -> (Hotel)x)
    .collect(Collectors.toList());
Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

Yes, there are a few ways to do this. One is to use the getClass() method. Because this is defined in the Object class, it can be called on every Java object.

System.out.println(myObject.getClass());

or even

if (myObject.getClass() == MyClass.class)

But if you only want to know whether an object is an instance of a particular class, you can write

if (myObject instanceof MyType)

which will return true if the class of myObject is MyType or any subtype thereof. You can use either an interface or a class for MyType here - even an abstract class.

However, as Tim pointed out in the comments, often there are better ways to design your program than relying on one of these ways of checking the class of an object. Careful use of polymorphism reduces the need for either of these.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • Just to point it, i edited my question. Forgot to mention that accomodation is an abstract class. However, "myObject" is going to point the dynamic type, right? The type that has been used to create the object, not to declare the variable. So.. This should works? if (array[index] instanceof Hotel) -> add to new array – Miruuu Dec 20 '17 at 04:29
  • Yes, `if (array[index] instanceof Hotel)` should work. – Dawood ibn Kareem Dec 20 '17 at 04:30