UnderWood
UnderWood

Reputation: 883

Type casting between unrelated classes

Let there be two classes defined as follows:

Class A{
    int a;
}

Class B{
    int b;
}

A and B are two unrelated classes. Is there anyway I can cast an object of A to B? If yes, please explain the various options I have.

Upvotes: 0

Views: 2674

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533492

You can do

Object b = new B();
A a = (A) b;

But this will throw a ClassCastException at runtime.

Instead you can use a copy Constructor

class B {
    public B(A a) { ... }

    public static B toB(A a) { return new B(a); }
}

And then you can do

B b = new B(a);

or

B b = toB(a);

Upvotes: 2

ZhongYu
ZhongYu

Reputation: 19682

You can do an upcast to a common super type, followed by a downcast

    (Dog)(Pet)aCat

Of course, Object is the supertype of any type, so we can use it to cast between any 2 types

    (Apple)(Object)aCat

Usually, this makes no sense, and it will cause runtime exception. But it may be helpful in some generic cases. For example, Supplier<Integer> and Supplier<number> are "unrelated"; as a matter of fact, they are mutually exclusive, i.e. the intersection is empty, or, no object can belong to the two types at the same time. Nevertheless, we may want to cast Supplier<Integer> to Supplier<Number>, due to lack of variance in Java, combined with the existence of erasure. See this case study.

Upvotes: 1

Jor El
Jor El

Reputation: 199

Though JAVA allows you to type cast object across unrelated classes i.e. which are not in class hierarchy. This is allowed because of the below case

String s = (String)list.get(1);

Well list can certainly contain different type of object and while calling such a method it could return String as well.

Coming to your question you will succeed in typecasting but at runtime you will get ClassCastException .

You can type cast object B to type A iff B IS-A A that means B is a subtype of A. If both are not in a hierarchy then type casting them does not make sense. just like you can not type cast an Animal type to Furniture type.

Upvotes: 0

NRitH
NRitH

Reputation: 13893

You can't. That would break a fundamental principle of object-oriented programming.

Upvotes: 0

Related Questions