• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

RuntimeException

 
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Does this code throw RuntimeException?

I tried no error and no exception.
This I found in MasterExam and the answer says Line 1 will throw RuntimeException however will compile fine.

Thanks
 
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I had tried a similiar program.
You are trying to downcast t1 to T2.ie. parent class to base class.
In that case (for me and as mentioned in the book) it threw a Class Cast Exception.
Because during compile time the compiler thinks that t1 can be of type T2.
But doesn't know that for sure.
When it runs,it realises its not and throws a class cast exception.
Try writing a method and inheriting it.And writing a complete new method in the base class.
And try accessing the base class (new) method with an object of parent class(after type casting it to the base class)
You will get an exception.

Hope it made a little bit clear.
 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You have to make the following change in the code:
class T1{}

class T2 extends T1{}
class T3 extends T1{}
public class Test{
public static void main(String []arg)
{
T1 t1=new T1();
T2 t2=new T2();
T3 t3=new T3();
t1=t2;//line1
t2=(T2)t1; //line 2
}
}
See at line 2 t1 is typecasted to T2...
Type of the actual objet denoted by reference at runtime, is checked...
In your program the reference t1 was denoting objet of class T1..
Now in the above program at runtime, reference t1 is denoting objet of type T1...so no runtime exception..
Hope this clears....
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic