Cannot cast to an Extended Class in Java

Joshua Pinter picture Joshua Pinter · Dec 6, 2013 · Viewed 9.8k times · Source

I looked around for a similar issue but couldn't find anything that matched it.

I'm trying to extend the built-in JSONObject to add some functionality, like so:

public class MyJSONObject extends JSONObject {

    // Easily return an integer from a JSONObject, handling when the value is null.
    //
    public Integer getIntegerUnlessNull(String key) throws JSONException {
        String key_value = this.getString (key);

        if ( key_value.equals("null") ) {
            return null;

        } else {
            return Integer.parseInt( key_value );
        }
    }
}

However, when I try to cast it, I get a java.lang.ClassCastException error:

private JSONArray    jsonClients;
        MyJSONObject clientJSONRecord;

clientJSONRecord = (MyJSONObject) jsonClients.getJSONObject(0);

The full error message is:

java.lang.ClassCastException: org.json.JSONObject cannot be cast to com.insightemissions.trak.extensions.MyJSONObject

Any help?

Cheers,

JP

Answer

Szymon picture Szymon · Dec 6, 2013

jsonClients.getJSONObject(0) returns an object of the type JSONObject which is your parent type.

You cannot cast it to the inherited type. It only works the other way, i.e. casting an inherited class to a parent class. This has nothing to do with your objects in particular, it just the way inheritance works.

Because you get an instance of JSONObject from the method and you cannot control how it's instantiated, you could add a constructor to your MyJSONObject class to create an object from the parent object:

public MyJSONObject(JSONObject parent) {
    super(parent.toString());
}

And use it this way:

JSONObject parent = jsonClients.getJSONObject(0);
MyJSONObject child = new MyJSONObject(parent);