Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • 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!!!
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!