final and private static
I read that doing:
public final void foo() {}
is equals to:
private static void foo() {}
both meaning that the method is not overridable!
But I don't see the equivalence if a method is private it's automatically开发者_高级运维 not accessible...
It's true that you can not @Override
either method. You can only @Override
a non-final
instance method.
- If it's
final
, then there's no way you can@Override
it - If it's
static
, then it's not an instance method to begin with
It's NOT true that they're "equal", because one is private static
, and the other is public final
.
- They have different accessibility level
- The instance method requires an instance to invoked upon, the class method doesn't
- The class method can not refer to instance methods/fields from the
static
context
You can not @Override
a static
method, but you can hide it with another static
method. A static
method, of course, does not permit dynamic dispatch (which is what is accomplished by an @Override
).
References
- JLS 8.4. Method Declarations
- 8.4.3.2 static Methods
- 8.4.3.3 final Methods
- 8.4.8 Inheritance, Overriding, and Hiding
- 8.4.8.1 Overriding (by Instance Methods)
- 8.4.8.2 Hiding (by Class Methods)
Related questions
- Polymorphism vs Overriding vs Overloading
- Why doesn’t Java allow overriding of static methods ?
- Static methods and their overriding
- When do you use Java’s @Override annotation and why?
Neither can be overridden, but for very different reasons. The first is a public nonstatic method, while the secod is static. So the first is not overridable only because it has been declared final, while the second, being static, can never be overridden.
Note that from the first you can access nonstatic members of the class, while from second you can't. So they are used in very different ways, thus are not "equal".
精彩评论