• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting

 
Mugdha Deo
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This is a question from marcus greens's exam # 1. Q17
I thought the answert would be 1, but the answer is 3.
Can some one please explain?
Thanks,
Mugdha.

What will happen if you attempt to compile and run the following code?
1) Compile and run without error
2) Compile time Exception
3) Runtime Exception

class Base {}
class Sub extends Base {}
class Sub2 extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=(Sub) b;
}
}
 
Rajiv Ranjan
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mugdha,
This is because you are trying to squeeze a super class into a subclass.
Sub s=(Sub) b; // not desirable.
This will work during compilation as but will throw a runtime exception.
Rajiv
 
Nasir Khan
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There won't be any error if
class Base {}
class Sub extends Base {}
class Sub2 extends Base {}
public class CEx{
public static void main(String argv[]){
Base b;//no need to initilized
b=new sub();// for avoiding runtime error
Sub s=(Sub) b;

}
}
 
Mugdha Deo
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

So,
Does it mean that upward casting or explicit casting always result in runtime errors?
Thanks,
Mugdha.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will always get a run time error if you cast an object into something it is not. A Base object is not a Sub object so casting a Base object into a Sub object will generate a run-time error.
 
Nissi Hari
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just Remember that casting of references is fine if it goes upwards in the inheritance tree . Suppose u create a sub object(using new), which is the subclass and cast it to a Base object it is fine.Because in this case you are going up the in inheritance hierarchy.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic