0

Is it possible to use constructor of class of diffrent object? Imagine two classes: A and B extends A. We make object

A x = new B(arg);

And then (pseudo-code!)

A y = new (x.getClass())(arg);

Can I reach this effect without iffing and casing through all possible inheritors of A?

radrow
  • 6,419
  • 4
  • 26
  • 53

2 Answers2

2

Reflection is probably what you want, still it's not encouraged:

A y = x.getClass().getConstructor(ArgType.class).newInstance(args);

Will create a new instance of B.

credits for @Hogler, for pointing out a mistake.

Mordechai
  • 15,437
  • 2
  • 41
  • 82
0

You can typecast the object if one object inherits the other. Look at this link for more information: Casting objects in Java

Community
  • 1
  • 1
ksivakumar
  • 481
  • 2
  • 5
  • 19