2
//Class defined in external jar
class A{
    many methods...
    public getId() {};
}

//I want to extends this class and overwrite single method
class MyA extends A{
private int myId;
public getId() {return myId};
}

void main ()
{
  A a = Factory.getA(); //External class create the instance
  MyA mya = (MyA)a;     //runtime Error!! I want to convert A to myA
}

Hi, I want to extends an instance which I get from external Jar and overwrite a single method getId(). I don't control the creation of the instance so the only solution I got was to pass it to my constructor and init all members manually, example here:

class MyA extends A{
private int myId;
public MyA(A a, int myId)
{
    this.myId = myId;
    //init all other methods from a.? to this.?
    this.setXXX(a.getXXX());
    this.setYYY(a.getYYY());
    ....many methods...
}
public getId() {return myId};
}

Is there a better way?

user3369398
  • 227
  • 2
  • 9
  • 1
    No, there's no better way. You can't downcast `A` to `MyA` any more than you can cast an `Object` to a `String`. The factory created an `A` and it'll stay an `A` unless you convert it to `MyA` somehow, for example with your constructor. – Kayaman Mar 04 '15 at 12:40
  • You could use reflection to modify the behaviour of A. – Tschallacka Mar 04 '15 at 13:07

2 Answers2

0

MyA mya = (MyA)a; //runtime Error!! I want to convert A to myA Is a an instance of MyA?? You can not convert if it is not an instance of MyA. you get java.lang.ClassCastException.

Chowdappa
  • 1,580
  • 1
  • 15
  • 31
0

Rather than getting all data from A in the constructor of MyA (and thus reimplementing it completely), create an Adapter, change the methods you need and in the rest just pass the calls to the original instance of A:

class MyA extends A{
private A adaptee;
private int myId;

public MyA(A adaptee, int myId)
{
    this.adaptee = adaptee;
    this.myId = myId;
}

// Override the method you need to 
@Override
public getId() {return myId};
...
// Override the rest of the methods so they call the adaptee.
@Override
public X getXXX() {
   return a.getXXX();
}
@Override
public void setXXX(X x) {
   a.setXXX(x);
}
...
}

Then, of course, use it as:

 A a = new MyA(Factory.getA(), myId);
... a.getId();
david a.
  • 5,283
  • 22
  • 24