Categories

JAVA DATEBASE
Technology Network Community
Oracle Database
Fusion Middleware
Development Tools
Java
Desktop
Server & Storage Systems
Enterprise Management
Berkeley DB Family
Cloud Computing
Big Data
Business Intelligence
Architecture
Migration and Modernization
E-Business Suite
Siebel
PeopleSoft Enterprise
JD Edwards World
Industries
JD Edwards EnterpriseOne
User Productivity Kit Pro (UPK) and Tutor
Governance, Risk & Compliance (GRC)
Master Data Management (MDM)
Oracle CRM On Demand
On Demand: SaaS and Managed Applications
AutoVue Enterprise Visualization
Primavera
ATG
Agile PLM
Endeca Experience Management
Fusion Applications
Archived Forums

 



Tags

New To Java


Casting Objects - Can someone explain why Casting Objects are used?


I am still new and not understanding what is on sun's website.   I am looking for a more generalized reason why Casting Objects is used, and possibly include an example.  Edited by: DJMegabit on Feb 23, 2009 3:27 PM

Casting Objects? I suggest you post some code to illustrate this novel turn of phrase.

Here is some code on what I was asking that I need a better clarification on why it is used.  Employee emp = new Employee(); VicePresident veep = new VicePresident();     emp = veep; //No cast needed for upward use   //Either can be used   veep = (VicePresident)emp; //must cast explicitly 

DJMegabit wrote: Employee emp = new Employee(); VicePresident veep = new VicePresident();   emp = veep; //No cast needed for upward use veep = (VicePresident)emp; //must cast explicitly   That just called "casting".  emp = veep; ^^^ No cast is needed because a VicePresident is an Employee.  veep = (VicePresident)emp; ^^^ A cast is needed because not every Employee is a VicePresident. The cast expresses "check at runtime this really references a VicePresident object (or is null)."

Why is the casting used? Is it based on the contents of the objects?

I can't explain it better than the tutorial. [Here you go|http://java.sun.com/docs/books/tutorial/java/IandI/subclasses.html].  If you still have questions, where here for you 

Yeah I read that.  I am try to come up to the reason logically why it would be needed.   Can someone help me rationalize the tutorial in to a bit more beginners terms.   If you have an example of some code that uses casting or can write some. I really am a visual learner. Please post   I guess I don't really understand why you would need to set one object equal to another.

Lets assume a visePresident object inherits from an employee object. This means in addition to the functions in an employee object (getFirstName, getLastName) that all employees have, visePresident has additional functions that normal employees do not have (getPresidentsAttention()  ).  When you cast a VisePresident object as an Employee object, what you are doing is hiding all the functions in the visePresident object except the ones from the employee object. In other words, you can only access firstName and lastName. If thats all you are interested in, you can cast it.  Lets also assume President object inherits from employee and so does Senator object.  You have an arrayList of President, Visepresident, Senator, and various other types of employees. You want to loop through the arrayList and get their first and last name. You dont care about the other functions. Then what you do is cast them all to Employee object and call those two functions.  Employee emp = new Employee(); VicePresident veep = new VicePresident();  *****    By the way, the following will not work since you cant cast an employee to visePresident. Why? The cast to VicePresident says 'veep' can now access the getPresidentsAttention() function. However, an employee object does NOT have a getPresidentsAttention() function! When veep attempts to call that function, it will fail (or more likely, not even compile): VicePresident veep = (VicePresident)emp; //must cast explicitly

@ the OP.   1) There are 2 types of casting Explicit and implicit.  Implicit = automatic = takes place when the variable that is being cast is small enough (byte size) to fit into the target variable. eg. int can be cast into long implicitly because long is big enough to fit anything that can legally fit into int.  Explicitly = you provide the cast and get a class cast exception if various requirements are not meant. You can read up about this all over the web. A vague example would be that anything in java can be cast into an Object(class) because everything in java is an Object. But there are many factors that need to be fulfilled as mentioned so do a search.

Read the original.  The Java Language Specification: [_15.16 Cast Expressions_|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.16] And in more detail: [_5.5 Casting Conversion_|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.5]  db

Example: class Wooster  extends JFrame  implements ActionListener { // ...  } public class Berty {   Wooster w;   public Berty(ActionListener al) {     w = (Wooster)al;   } } 

That piece of code doesn't even compile. It is not an example of anything relevant to this thread.

DJMegabit wrote:  I am looking for a more generalized reason why Casting Objects is used  Sometimes the compiler just cannot decide at compile-time whether for example an assignment is correct. Instead it says: Sorry but I cannot check this now. You'll have to show your intentions by making a cast. I'll come back later at runtime to make sure you didn't try to fool me. If you did I'll throw a bad cast exception.  So the generalized reason is type-safety. The compiler does the best it can to ensure type-safety at compile-time. If it cannot, it enforces a cast thereby making you responsible for the situation. It then checks at runtime that the cast you made was correct indeed. Otherwise it throws.

ejp wrote: That piece of code doesn't even compile. It is not an example of anything relevant to this thread.  HuH? Of course it doesn't compile - it's an example of casting usage, not writing useful code.  ~Bill

HuH? Of course it doesn't compile - it's an example of casting usage, not writing useful code. Huh? It's not an example of anything. It is not a valid Java program. It illustrates nothing, and specifically it doesn't answer the OP's question.


Related Links

Expanding Sets
New to Java, simple question!
Loading different library versions
How to change a java file to a C++ file.
Helppp Plzzz, My Java work needs to be done by 2mrw, Im new 2 java.
Simple Trivia game
WTF? Stupid Question...
Creating Objects and Passing Variables to them?
Properties file problem
Calendar class shows counts december as 11
Different applet similar internet explorer problems
identifier expexted??
Calender:Obtaining days/weeks/months between a start & end Calendar range
objects and subclasses
How to distribute a JNLP
Swing confusion...