I created a class called "Object" and two classes "Item" and "Scenery"
that implement the class Object ( every item is an object and every
scenery is an object )
In Java, every object is an instance of Object
, so you don't need explicitly to make Item
and Scenery
subtypes. Also, Object
it's a class so we use to say implement
with abstract types like Interfaces
and extends
for concrete elements.
To determinate what type is the object, you can use instanceof
Object[] myObj = {new Item(),new Item(), new Scenary()};
for (Object s : myObj)
if (s instanceof Item)
System.out.println(s.getClass() + " It's an item!");
Pay attention that instanceof
return true also with subtypes. So let's assume in future you will extend the Item
class with another class let's call it SubItem
. If the array of objects contains some SubItem
instances, the instanceof
call on SubItem
will return true. So if you want to determinate precisely if it's the right class object you need a more restricted check just like s.getClass() == Item.class
.
Object[] myObj = {new Item(), new Scenary(), new SubItem(),new SubItem()};
for (Object s : myObj)
if (s.getClass() == Item.class)
System.out.println(s.getClass() + " It's an Item!");
In this latest scenario, this check will return true only if s
is effectively a Item
and not a SubItem
.
As the latest point don't use Object, always use abstract class or interfaces to aggregate more types. If you will continue to study you will understand why. So what I'm saying is to create an interface for example Shop
and let both Item
Scenery
and eventually SubItem
implement it. Take notes that with this method both the 3 types are subtypes of the type Shop
so a instanceof
for each Item
Scenery
and SubItem
compared with Shop
will return true.
Summering: instanceof
will be useful for runtime checks when you have an abstract type and you can't determinate statically the real nature of an object. (Imagine to assign an instantiated Item
to it's Shop
for example Shop obj = new Item();
. You will notice that this assignment is legit.