Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static method can be overridden?

 
Song Guo
Greenhorn
Posts: 24
Chrome Java Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

<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 !
Screenshot-47.png
[Thumbnail for Screenshot-47.png]
what the compier saied
 
harshvardhan ojha
Ranch Hand
Posts: 157
1
Android Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 924
1
Fedora Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic