• Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting  RSS feed

 
Sam Saha
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote a method which returns an object of class type Fault. Now I want to assign it into another object of type Acknowledge. These two classes are not related to each other. How would I cast and assign. I am new to java. I would appreciate if someone can help me how to do this. Thank you very much.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't.

Casting doesn't actually change the underlying object at all. It is just something you can do to tell the compiler "hey, I know you think I shouldn't be able to do this, but TRUST ME...I know what I'm doing and it will be all right".

If then at run time the object isn't the right type, you will get an error.

update: also, you don't "assign it into another object of type Acknowledge". you assign it to a reference to a type Acknowledge - or in this case, you don't.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sam Saha wrote:I wrote a method which returns an object of class type Fault. Now I want to assign it into another object of type Acknowledge. These two classes are not related to each other. How would I cast and assign.

First: What Fred said.

Second: From the sound of it, you want an acknowledgement to include a reference to the Fault that caused it; and that's dead easy - just make it a field in your Acknowledge class and pass it whenever you create one.

BTW: Classes normally have nouns as names, and "acknowledge" is a verb, which are more often used for methods. 'Acknowledgement' might be a better choice; or possibly 'Response' if you want to save typing.

It's not a hard-and-fast rule, but people may find your programs easier to follow if you use it as a general guideline.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!