• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object Doubt

 
Karthikeyan Pandian
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
11. class Alpha {
12. public void foo() { System.out.print("Afoo "); }
13. }
14. public class Beta extends Alpha {
15. public void foo() { System.out.print("Bfoo "); }
16. public static void main(String[] args) {
17. Alpha a = new Beta();
18. Beta b = (Beta)a;
19. a.foo(); 20. b.foo();

// Please explain me the line 18 and 19, i am new to java.
 
Ganesh Jee
Greenhorn
Posts: 14
Eclipse IDE MySQL Database Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
line 18, Beta b = (Beta) a // It is required to cast as you can not assign a super class reference to a subclass reference directly
line 19, a.foo(), b.foo() // Here you making use of super class reference (which is pointing to sub class object), subclass reference( which intern pointing to sub class object) to invoke foo() method. So, both will invoke subclass method.
 
Karthikeyan Pandian
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Ganesh Jee... I understood clearly ..Cheers!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic