• Post Reply Bookmark Topic Watch Topic
  • New Topic

Inheritence | Static Method Behaviour  RSS feed

 
samarth mishra
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.



 
Jhon Calado
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.
 
Henry Wong
author
Sheriff
Posts: 23295
125
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
 
manish ghildiyal
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
 
Ulf Lindqvist
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).
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!