db2791 db2791 - 1 year ago 70
Java Question

Java converting from Object to Subclass

Here is my code for Scene.java. It has different types of objects, all of which are included in one common ArrayList called

. All of them share a
method that returns their identifier. I want to use the
list to determine if there is any object in the scene that matches a given identifier, regardless of its type:

ArrayList<NPC> npcs = new ArrayList<NPC>();
ArrayList<Item> items = new ArrayList<Item>();
ArrayList<EnviromentalObject> enviromental_objects = new ArrayList<EnviromentalObject>();

ArrayList<Object> targets;

public Object check_for_target(String target_name){
for (Object target : targets){
if (target.toString() == target_name){
return target;
return null;

Here is the code in Game.java, which checks for a given identifier. If there is a match ion the current scene, I want to know the object's type and treat it as its true type. Right now, I have the following code, and I knew it wouldn't work, but maybe it'll help get my idea across.

Object target = current_scene.check_for_target(target_name);
if (target == null){
} else {
String target_type = target.getClass().getName();
target = (target_type) target;

What would be the correct way of getting the object's type and then being able to use that object's methods? Right now, I'm only given
's methods. Do I create a superclass for
, and

Answer Source

Basically, you can check if an object is an instance of a specific class.

it could be something like this :

if( target instanceof NPC) {
    System.out.println("target  is a NPC");
  else if( Target instanceof Item) {
    System.out.println("target is an Item");

  if( target  instanceof EnviromentalObject) {

    System.out.println("target is EnviromentalObject");