GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "casting" Watch "casting" New topic
Author

casting

Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531


can anyone explain why i get an error at line 2 and not at 1?

without the cast both give incompatible types...but with cast i get an error at 2...(convertible type) but not at 1

Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18874
    
  40

Ankur kothari wrote:
can anyone explain why i get an error at line 2 and not at 1?

without the cast both give incompatible types...but with cast i get an error at 2...(convertible type) but not at 1


Just because the compiler doesn't complain about a cast, doesn't mean that the cast is legal -- it just means that the compiler can't detect the issue at compile time. In this case, it will throw an exception at runtime.

The reason the compiler can't detect it is -- technically is possible to create an instance that is both IS-A Ankur and IS-A AnkurInterface, even through the AnkurInterface class doesn't implement the Ankur interface.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Sonali Sehgal
Ranch Hand

Joined: Jul 09, 2009
Posts: 75



You get an compile time error at line 2 and not at line 1.This is right.

At line 1 the interface object it gets executed successfully because Car is an

instance of Move Interface which returns true and hence the handle of the interface

can point to Car.

But at line 2 the object car is not an instance of the Vehicle neither it implements

Interface neither Vehicle is the super class of the car. In interface the concept is when you create an interface you are defining the contract for what a class can do .Hence it gives a compile time error of incovertible types .In this case this error can be fixed only byt adding the line to public class car extends vehicle implements move.Then your program is right.
rohan yadav
Ranch Hand

Joined: Oct 13, 2009
Posts: 156
You get an compile time error at line 2 and not at line 1.This is right.

At line 1 the interface object it gets executed successfully because Car is an

instance of Move Interface which returns true and hence the handle of the interface

can point to Car.


I didnt get it how car is an instance of move??since car not implementing move??


Sage of The Monstrous Toad of Mount Myoboku
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18874
    
  40

rohan yadav wrote:I didnt get it how car is an instance of move??since car not implementing move??


It isn't. And it doesn't. Which means at runtime, you will get an cast exception.


However, all you are doing is casting an instance being referenced by a car reference, so it can be assigned to a move reference. It is not always true that a car reference will point to an intance of a Car class, it just needs to reference something that IS-A car, which can be an instance of the car class. Or something that is a subclass of the car class, which also can implement the move interface.

Henry
rohan yadav
Ranch Hand

Joined: Oct 13, 2009
Posts: 156

Is it ok to cast a car object to Drive refrence variable??


Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18874
    
  40

rohan yadav wrote:Is it ok to cast a car object to Drive refrence variable??


What happened when you tried it?

Henry
rohan yadav
Ranch Hand

Joined: Oct 13, 2009
Posts: 156
Oh its not giving compile time error.
Now i understand we can assign any class object to any interface refrence variable through casting.
But we cant do it for classes(in this case vehicle and car).
Am i right???
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
absolutely dude....bang on target
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18874
    
  40

rohan yadav wrote:
Now i understand we can assign any class object to any interface refrence variable through casting.
But we cant do it for classes(in this case vehicle and car).
Am i right???


Actually, no... Basically, if the compiler can determine that the assignment is not allowed at compile time, it will not compile. In the case of assigning an object, held by a reference, being casted and assigned to another reference (for an interface), it is just harder for the compiler to make such as determination.

You can actually get the assignment to fail to compile. In this example, try changing the car class to a final class.

Henry
rohan yadav
Ranch Hand

Joined: Oct 13, 2009
Posts: 156
How compiler can determine whether it is correct cast or not??
If there is any document for this can you tell me the link
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
hey actually the compiler just assumes that the casting will work but you are bound to get a runtime exception if at runtime the casting is not proper...

Sonali Sehgal
Ranch Hand

Joined: Jul 09, 2009
Posts: 75



Compiler can determine the cast is correct or not by only one way
say in the above program the handle car can only be instanceof Move and Vehicle..
you can run this program by the following test.


the output of the above will be true true.

Let me be more specific the car is instance of Move and Vehicle only if the public class car extends Vehicle and implements Move
otherwise at runtime it will throw an class cast exception..only incase if you do not extend Vehicle and implement Move as incase of code 1 and line 2 as
Vehicle v1=(Vehicle)car;//2

Syntax of casting upcasting or downcasting is
Destinationtype handle=(destination type) handle/instance;
As you mentioned in line 2 Vehicle v1= (Vehicle) car and you are not extending Vehicle this is forceful personification and it will throw a class cast exception.
Sonali Sehgal
Ranch Hand

Joined: Jul 09, 2009
Posts: 75
Hi Ankur and Rohan,
I have again mentioned the above casting explanation and to let you know more about casting it is as follows:-




Moving up in the inheritance hierarchy it is called upcasting
Car c=(Vehicle) new Nano(); //Compile Time Error
if you do
Car c=(Car) new Vehicle();

It will throw Class cast exception.
Car c1=(Car)v1;// This is called Downcasting.
//With the help of downcasting you can invoke any method of Car class
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18874
    
  40

Ankur kothari wrote:hey actually the compiler just assumes that the casting will work but you are bound to get a runtime exception if at runtime the casting is not proper...


As already mentioned, this is not true. Under certain conditions, the compiler is able to determine that the cast is not legal. For example...



Henry
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
hey sonali you are going off topic....



you said that move can refer to car...but how...they are not even in the heirarchy
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
hey henry by the way what did you do to my javac post?
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531


line 1 compiles but gives a run time exception....what are the ways of removing that exception other than making AnkurInterface implement Ankur
Sonali Sehgal
Ranch Hand

Joined: Jul 09, 2009
Posts: 75
Hi Ankur ,
back to your point at the very first program...............I have explained it again..this is the second solution to it.....in the other scenario..


line 2 will not compile but at runtime it will give Class cast exception.
line 2 will not compile only because we are doing a forceful personification.
Compiler also reports an error where it says
inconvertible types
found: Car
required :Vehicle
Vehicle v1=(Vehicle)car;//2


1 error

In the above line it is an error as car instance of Vehicle returns false and line 2 is giving a compile time error
the compiler also says found car but required Vehicle which means Vehicle v1=(Vehicle) new Vehicle();
This means this is what you can do in your program and this is the only right one.
That means you can only make a handle of Vehicle and create an instance of it.

For the line 1 you cannot execute it as Car cannot be casted to Move by anyway and this is what the exception exactly for.

rohan yadav
Ranch Hand

Joined: Oct 13, 2009
Posts: 156
Hi Sonali, Henry and Ankur Thanks for your explanation.
But sorry to say that i didnt understand it.
I have following doubts please can anyone explain this:
1. Why we can cast class object into interface type but not into another class type??
(I want to say that if we can cast class car into Move then why we cant cast car into vehicle class as both Vehicle and Move dont have any reference with class Car. )By the way when i say allowed i mean compiled.(How they are compiled)

2. What are the references to study casting??


Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
sonali is one competitor.....see how many posts she has given to explain it to me..thanks sonali
rohan yadav
Ranch Hand

Joined: Oct 13, 2009
Posts: 156
Hi Ankur i toattly agree with you
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
1. Just you have to become compiler for this purpose.
2. Second you have to think in terms of subclasses to understand this funda. just interms of subclasses.
3. Remember : subclasses cannot inherit more than one class
means

not allowed.
4. You have to think in terms of class hierarchy.

Now everything will become crystal clear.

first doubt:
why we cant cast car into vehicle class ?


First of all if compiler sees this line:


It thinks in terms of subclass also.
1. It sees whether Car is subclass of Vehicle.


ans: no

2. It sees whether Car's subclass like FerrariCar is Vehicle

ans : no
Means now compiler is 100% sure that Car is not coming in the Tree or hierarchy of Vehicle.
So it says I know this is not possible.

Second doubt:
Why we can cast class car into Move ?


Ans is as this is possible :


Here FerrariCar is both Car and Move.

Move m1=(Move)car;//1

so compiler thinks interms of:
1. car reference type is Car. So it can point to either instance of Car or instance of SubClasses of Car.
means Car car = new FerrariCar(); also possible.
2. SubClasses of Car can also implement Move interface, but compiler cannot do this cross checking at compile time, as it comes clear only at runtime.
3. So compiler says, I donot have idea between subclasses of Car and Move relationship.
4. Compiler says, I cannot decide where subclasses of Car and Move are in a hierarchy, belongs to same tree.
5. So it leaves everything for this relationship for the java Runtime.

and Java Runtime sees Car, subclasses of Car and Move do not belong to same tree, so it gives ClassCastException.







SCJP 6
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
hey punit that was beautiful...believe me....but why cant the compiler do checking if there is a heirarchy relationship between move and car subclasses?

i think i missed it?
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
And if you want answer in one line than:

Subclasses of Car cannot extend Vehicle, but can implement Move.

rohan yadav
Ranch Hand

Joined: Oct 13, 2009
Posts: 156
Thanks Punit. Great Explanation man. I must say!!!

Where did You find these kind of stuff?? I mean what is the reference through which you study all this??
What material i have to study so that i can master java like urself??
Currently i am preparing for SCJP exam
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
you mean to say that Move m =(Move)Car is allowed because it might happen that car variable is itself referring to a subclass that implements move?
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
Ankur kothari wrote:hey punit that was beautiful...believe me....but why cant the compiler do checking if there is a heirarchy relationship between move and car subclasses?

i think i missed it?


As subclasses are not loaded loaded in the heap memory, and at compile time there is no way to decide what Car is referencing to. These are the construct that is dynamically loaded and decided.

At compile time Object pointed by Car reference variable does not get loaded into heap memory and simple reading heap memory and deciding what object is living there is not possible at compile time. You have to run your program, after run these memory are loaded and after run it is the job of Runtime JVM.
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
Ankur kothari wrote:you mean to say that Move m =(Move)Car is allowed because it might happen that car variable is itself referring to a subclass that implements move?


Exactly

Just make a sample for this concept, it will help you in future.
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531



this compiles.......great...awesome

i mean this not only compiles but also runs.....this was the reason there was a runtime exception before
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
rohan yadav wrote:Thanks Punit. Great Explanation man. I must say!!!

Where did You find these kind of stuff?? I mean what is the reference through which you study all this??
What material i have to study so that i can master java like urself??
Currently i am preparing for SCJP exam


Well for my case, I was good in c++ pointer and oops in c++. So I learned these from c++.
But for java SCJP 6.0 K&B, I think Head First Java is also good for this concept, and through lots of programming, and discussions at javaranch.
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
Hey Rohan when there are guys like Punit...Ankit...Henry....Sonali....to help you...life becomes easy
rohan yadav
Ranch Hand

Joined: Oct 13, 2009
Posts: 156
Exactly Ankit i totally agree with. They are genius. I want my programming to become like them
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
dude i am Ankur not Ankit
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
rohan yadav wrote:Exactly Ankit i totally agree with. They are genius. I want my programming to become like them


Soon you both will become genius, just discuss here, many good people had come when I was preparing for SCJP, Ankit Garg was there already, but good people like Ruben Suto, Sachin Aadat are not visiting this forum now, may be there were too much busy.
rohan yadav
Ranch Hand

Joined: Oct 13, 2009
Posts: 156
Sorry Ankur. Can i know when are you planning to give SCJP exam?
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
first i was planning to give on dec 6th..but now i think i would be delaying it...maybe by a month
 
GeeCON Prague 2014
 
subject: casting