This week's book giveaway is in the OCP forum.
We're giving away four copies of OCP Java SE 8 Programmer II Exam Study Guide and have Kathy Sierra, Bert Bates, & Elizabeth Robson on-line!
See this thread for details.
Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Inheritence | Static Method Behaviour  RSS feed

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know what is Static methods, but could not understand what is actually happening here:

when I call a1.a(), in case of non static methods it gives OUTPUT b.
But, in case HERE the OUTPUT is b.



 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey,

You are invoking a method from class b, so it gives you the output from that method:"b".
Object a1 is of the class b,whose a-method has overriden the a-method from class A.
 
author
Marshal
Posts: 23439
138
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

samarth mishra wrote:I know what is Static methods, but could not understand what is actually happening here:

when I call a1.a(), in case of non static methods it gives OUTPUT b.
But, in case HERE the OUTPUT is b.






When I ran it, I got "a" -- which is correct since inheritance doesn't apply for static methods. Are you sure that you got "b" with this code?

Henry
 
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Samarth,

I think output must be 'a', not 'b'. Static methods can't be overridden. Their call is resolved during compile time
itself, meaning that which version of method is to be called is decided by type of reference.
As in your case , reference is of parent type, so parent class's method is called.

Manish
 
samarth mishra
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

manish ghildiyal wrote:Hi Samarth,

I think output must be 'a', not 'b'. Static methods can't be overridden. Their call is resolved during compile time
itself, meaning that which version of method is to be called is decided by type of reference.
As in your case , reference is of parent type, so parent class's method is called.

Manish





Hey Manish, I got my answer. Thanks man. . N yea sorry for the output
 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Henry Wong wrote:
When I ran it, I got "a" -- which is correct since inheritance doesn't apply for static methods.



That's right.

Since static methods cannot be overriden the the compiletime type of a1 (which is A) will be used, and not the runtime type of a1 (which is B).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!