Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identical classes casting?

Suppose I have two classes A and B. Both are identical (same atributes, methods, etc), but they are named different.

There's some safe way, in Java, to cast a B object as an A object?

like image 535
riktro Avatar asked Oct 09 '10 22:10

riktro


2 Answers

No, you cannot cast one to the other if they belong in different class hierarchies. They are not identical, even if they happen to share the same attributes and methods. Additionally, if they belong to the same class hierarchy, but one is not a superclass of the other, you can't cast across the same class hierarchy either. There's only upcasting and downcasting within a hierarchy.

However, you can pass objects of either class to a certain method if

  • They implement the same interface, or extend the same superclass, and
  • That method accepts a parameter that is of the interface's or superclass's type

(And that's the basic premise of polymorphism.)

like image 150
BoltClock Avatar answered Oct 08 '22 17:10

BoltClock


No you can't, unless they have a common parent with the same attributes, but you can use the copyProperties() method from common.beanutils to pass every property from one bean to another.

Another way would be to create a subclass for A which could delegate calls to a B and vice versa.

A third way would be to use a proxy.

But the last two solutions only works for method calls, if your attributes are public you can't do anything.

like image 39
Colin Hebert Avatar answered Oct 08 '22 17:10

Colin Hebert