1

I have a class that I don't have access to its source.

public class IDontHaveAccessToSource {...}

I'd like to add some methods to it, like so:

public class MyClass extends IDontHaveAccessToSource {
    myMethod1() {...}
    myMethod2() {...}

    @Override
    methodInIDontHaveAccessToSource(){...}
}

but it will give me a ClassCastException whenever I want to cast anything that returns IDontHaveAccessToSource to MyClass.

How can I do such things?

I don't want to use

public class MyClass {
    IDontHaveAccessToSource obj;

    MyClass(IDontHaveAccessToSource obj) {
        this.obj = obj;
    }
    ...
}

And there isn't any constructor available for IDontHaveAccessToSource. It 'gets created' by calling a function from another class:

IDontHaveAccessToSource obj = loadObject(filename);
GhostCat
  • 137,827
  • 25
  • 176
  • 248
Gustavo Lopes
  • 3,794
  • 4
  • 17
  • 57

2 Answers2

1

You simply can't. An object that is created with new Super() can not be turned into a subclass object. If that would be possible, you would be able to break all rules of good object oriented programming.

You can only wrap around such objects. Think of decorator or facade patterns for example.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

You cannot cast the object of more general class to more specific one since there is no object data in memory that relates to that specific part of your child class. Say, you have class A that has a field fA. When you instansiate the object of that class, the field is initialized and takes some place in memory. Now you extend the class A to B by adding field fB. You create an object that allocates fA and fB in memory.

A aObj = new B(); is the proper cast since A knows about aF and once you access fA it will find the field in memory;

B bObj = new A(); This iswring since refering to bF won't be succeeded (instanciating of A did not allocate fB in memory)

Alexey R.
  • 8,057
  • 2
  • 11
  • 27