One way is to use the getClass()
method.
Object obj = vehicleIterator.next();
Class type = obj.getClass();
System.out.println("The type is: " + type.getName());
However, if you're explicitly checking class type there's almost always a better way to write your code using polymorphism or some other OO principle. Code that checks type like this, or using instanceof
, would certainly have to be changed if additional types of cars are added.
Without having more information about what you're doing with the type, I'd suggest you have a base type Vehicle
that Car
, Bus
, etc. all inherit from. Give your vehicles the methods they need (override the ones you need to) then just call those methods in your loop.