• 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
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Casting

 
Ranch Hand
Posts: 469
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[CODE}
class A{}
class B extends A implements E{}//line 1
class C extends A{}
class D extends B{}
interface E{}
public class Question07 {
public static void main(String[] args) {
A a = new D();//line 2
C c = new C();//line 3
E e = (E)a;//line 4
B b = (B)e;//line 5
}
}
[/CODE]
How come the above code compiles & runs fine.Shouldn't it give runtime error at line 4 ?coz class A does not implement interface E.
Veena
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Veena
The variable a is declared as a variable of type A, so it can refer to an object of type A or any of its subclasses. In this case it is refering to an object of type D, a D object is an A object becasue it extends B which in turn extends A. So a D object is a D object, is a B object and is a A object also. However, since class B implements interface E, a B object, and a D object by inheritance, is also an E object.
hope that explains it for you
 
Veena Pointi
Ranch Hand
Posts: 469
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I got it!
Actually after posting I noticed a is referring to D....I gotta be very careful while reading question....
Thanks
Veena
 
Legend has it that if you rub the right tiny ad, a genie comes out.
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic