Michael Japeson
Michael Japeson

Reputation: 33

Cast to type which is not inherited

I have class lets say

public class Magic implements Serializable{
}

and this class does not inherit

public class Amount{
}

Is there any way to cast Magic to Amount, I will be not accessing any fields what so ever, i just need Magic to "become" Amount? Is there any way?

Upvotes: 1

Views: 587

Answers (4)

Jesper
Jesper

Reputation: 207026

Casting does not automatically convert objects from one type to another type.

A cast is a way to disable the compiler's type checks. The only thing that a cast does, is tell the compiler: "Here is an object, and I know better than you what kind of object this is, so I want you to treat it as an object of this type, and not complain".

A type check will still be done, at runtime, and if at that time the object really is not of the type that you said it was, you will get a ClassCastException.

A cast cannot automatically convert a Magic object into an Amount object.

You need to write the code yourself to create an Amount object using the data of the Magic object.

Upvotes: 0

Stijn Van Bever
Stijn Van Bever

Reputation: 100

The only way to have Magic become Amount is to have your class: Magic extend the Amount class.

You want an is a link between classes and this is done by inheritance.

Otherwise you will receive a compilation error.

Upvotes: 0

Mureinik
Mureinik

Reputation: 312354

You can't cast between unrelated types in Java. If you need to create an Amount instance from a Magic instance you should have a constructor that receives such an argument:

public class Amount {
    public Amount(Magic m) {
        // Initialize amount's fields...
    }
}

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234885

No there isn't. An instance of Amount is unrelated to an instance of Magic.

This is true even if the two classes look identical, which in your case they certainly are not.

In this case, you need to suffer the pain of writing the code to convert Magic to an Amount. Perhaps have a constructor in Amount that takes a Magic instance as the parameter.

Alternatively, if Amount contains only functions, then consider recasting it as an interface, which is implemented by Magic.

Upvotes: 1

Related Questions