wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes static method can be overridden? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static method can be overridden?" Watch "static method can be overridden?" New topic
Author

static method can be overridden?

Song Guo
Greenhorn

Joined: Apr 24, 2011
Posts: 24


<SCJP> says "...Remember that static methods can't be overridden! This doesn't mean they can't be redefined in a subclass, but redefining and overriding aren't the same thing."
But this code confused me !



When I compile the code , the compiler said that "info() in Apple cannot override info() in Fruit; attempting to assign weaker access privileges"
It means static method can be overridden ? But <SCJP> says they cannot be overriden !



[Thumbnail for Screenshot-47.png]

harshvardhan ojha
Ranch Hand

Joined: Jul 26, 2007
Posts: 157
    
    1

class Fruit {
public static void info() {
System.out.println("fruit");
}
}

class Apple extends Fruit {

}

Here class level method info is extended in Apple, now if you will call Apple.info() this will five output as Fruit.

This means you wont achieve the intended purpose of overriding, i.e. calling a method depending upon its object at run time, so overriding has no effect but you have that method extended and access to code will be resolved at compile time you will get error if you happen to violate the overriding rules.
gurpeet singh
Ranch Hand

Joined: Apr 04, 2012
Posts: 924
    
    1

just because you got compiler error that don't assign weaker privileges does not prove that static methods can be overridden. for a moment ignore the error. or better assing public instead of protected. then create a new class and in the main method do this



it will print fruit. had there been overriding it would have print apple. overriding happens at runtime. it is late-binding. which method to called is decided at runtime. but here the call is decided on the basis of TYPE of f, which is Fruit. so no overriding.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static method can be overridden?
 
Similar Threads
Polymorphic calls
Protected method in a packaged superclass not being called by subclass
method in subclass not seeing method in abstract superclass
Why this exception ?
cant retrieve data.