• Post Reply Bookmark Topic Watch Topic
  • New Topic

non-static method overriding a static method  RSS feed

 
Timothy Sam
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will happen to the following? I had this in one of my applications and didn't know exactly what would happen...




and vice-versa... Another one like this...





Very tricky indeed...
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tricky? It won't compile. In the first example the static method hides the instance method which is a compile-time error. In the second example the instance method overrides the static method, which is also a compile-time error.
 
Timothy Sam
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, thanks for you reply! Now I'm confident that I got all two answers right. I didn't fully understand the reason why though... So if anyone could explain in a Head First Java way, I would appreciate... Thanks!
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Timothy Sam:
So if anyone could explain in a Head First Java way, I would appreciate...


Do you mean accompanied by a big-headed image?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Timothy Sam:
I didn't fully understand the reason why though


Static methods can't override non-static methods, and vice-versa. It's in the language specification; there's no better "why" than that, nor easier to understand.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's too bad that static methods can be invoked using the syntax of instance invocation:

A a = new A();
A.staticMethod(); //preferred
a.staticMethod(); //allowed but poor style

If that were not allowed in the syntax, then it would have made sense to put static and non-static methods in separate namespaces. Then one would be allowed to have

in the same way one is allowed to have

This solution makes more sense to me, but it's too late to change it now.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!