• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interface - TypeCasting

 
Gautham Muralidharan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Why line 19 doesn't compile while line 20 produces the output 'SubType' ?
 
Mala Gupta
Author
Ranch Hand
Posts: 363
11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On line 19, because (Inter) b.print() tries to cast b.print() to type Inter, it doesn't compile.

On line 20, ((Inter) b).print() casts 'b' to 'Inter' and then calls method print(), which is correct.

With much respect,
Mala
 
Narayana Bojja
Ranch Hand
Posts: 135
4
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gautham,

Why line 19 doesn't compile



Line 19 doesn't  compile because you are calling print( ) method on reference variable b which is a type of Type class . But Type class doesn't has print( ) method so compiler gives you error saying print( ) method is undefined for type Type. After calling print method on Type class reference and then you are casting to Inter. That's incorrect.

while line 20 produces the output 'SubType' ?


This is correct way of casting. First you are casting b to Inter type and then you are calling print method on b which is Inter type now. It compiles fine because Inter has print method and you have implemented print method in SUbType class.

Hope it helps
 
Gautham Muralidharan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You So Much Mala Gupta ji and Narayana Bojja ji!
Now I have understood it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic