alex
alex

Reputation: 29

Is there a way to change a superclass obj into a subclass obj?

I have an image class from a library and I'm trying to extend. The superclass methods return new superclass objects in several cases. How can I use the subclass methods on the objects returned by the superclass methods? Is there a way to change a superclass object into a subclass object?

public class LibraryClass extends SomeBaseClass {
    LibraryClass someMethodThatChangesDataReturningNewObject() {
    }
}

public class MyClass extends LibraryClass {
    // methods that extends functionality

    // possible to override superclass method calling it and turning the LibraryClass 
    // obj into a MyClass obj and return that?
}

someRandomMethod() {
    MyClass obj = new MyClass;
    LibraryClass newObj = obj.someMethodThatChangesDataReturningNewObject();
    // possible to bind my subclass methods to newObj?
}

Upvotes: 0

Views: 94

Answers (1)

Matthew Ammeter
Matthew Ammeter

Reputation: 84

Well, you can do something like this:

MyClass obj = new MyClass();
MyClass newObj = (MyClass) obj.someMethodThatChangesDataReturningNewObject();

You just need to make sure that your implementation of MyClass.someMethodThatChangesDataReturningNewObject() does in fact return an instance of MyClass. If your implementation of that method just calls a parent implementation, then you'll be safer wrapping the cast in an if statement as follows:

MyClass obj = new MyClass();
LibraryClass newLibraryClass = obj.someMethodThatChangesDataReturningNewObject();
if (newLibraryClass instanceof MyClass) {
    MyClass newObj = (MyClass) newLibraryClass;
    // MyClass specific processing here
}

In this case, if the object is not an instance of MyClass, you won't get a ClassCastException. Just keep in mind that if its not an instance of MyClass, then that processing won't get executed.

The only other way to do it would be to create a constructor or other utility method that can create a new MyClass instance using the data from the LibraryClass. That may or may not be possible, depending on whether the fields or getters/setters in LibraryClass are private, or protected/public. Without knowing any of the details of LibraryClass, its hard to say. But I would expect it to look similar to:

MyClass(LibraryClass libraryClass) {
    this.setField1(libraryClass.getField1());
    this.setField2(libraryClass.getField2());
    ...
}

Upvotes: 1

Related Questions