Reputation: 179
THis is my superclass:
class Superclass {
int a=89;
final static void m( int p){
System.out.println("Inside superclass");
}
static void n(){
system.out.print("superclass");
}
}
This is my subclass::
class Subclass extends Superclass {
int a=90;
static void m( int p){
System.out.println("Inside subclass");
}
static void n(){
system.out.print("subclass");
}
}
Main class:
class main {
public static void main(String[] args) {
Subclass.m(89);
new Subclass().n();
}
}
the problem is that i cannot understand why Javac is giving me overriding error in static method..an P.S plzz elaborate that all rules for overriding are also valid for hiding. like
The new method definition must have the same method signature (i.e., method name and parameters) and the same return type. Whether parameters in the overriding method should be final is at the discretion of the subclass method's signature does not encompass the final modifier of parameters, only their types and order.
The new
method definition cannot narrow the accessibility of the method, but it can widen it The new method definition can only specify all or none, or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the superclass
my error is: run:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - m(int) in javaapplication3.Subclass cannot override m(int) in javaapplication3.Superclass overridden method is static,final at javaapplication3.Subclass.m(JavaApplication3.java:18) at javaapplication3.min.main(JavaApplication3.java:25) Java Result: 1
also i want to ask if static members called from classname to resolve whicch version of method is executed when method is hidden by subclass extending the superclass what if i make anonymous object and then call method then how the compiler determines which version of method should be called. in above code in main class i type this: new Subclass().n();
how does the compiler know subclass version of method should be called even if i am not providing the type of reference variable
Upvotes: 2
Views: 3564
Reputation: 49372
From the JLS 8.4.3.3:
A method can be declared final to prevent subclasses from overriding or hiding it.
Static methods with the same signature from the parent class are hidden when called from an instance of the subclass. However, you can't override/hide final methods.
The keyword final
will disable the method from being hidden. So they cannot be hidden and an attempt to do so will result in a compiler error. There is a nice explanation on this on Javaranch.
Upvotes: 5
Reputation: 13066
What you are observing here is in accordance with JLS 8.4.3.3 which states that:
It is a compile-time error to attempt to override or hide a final method.
You are trying to override final static void m
method in subclass , which is not permitted by Java compiler.
Upvotes: 2