• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Q about polymorphism

 
Kathy Cai
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both show1 and show2 in Q2 class are overriding methods in the attached code. However if I run the code, I got the following results:
Show1 in Test class
Show2 in Q2 class
That is, show1 in Test class was not overridden. I don't know why modifier "static" caused this. I appreciate your explanation.
----
class Test {
static void show1() {
System.out.println("Show1 in Test class"); }
void show2() {
System.out.println("Show2 in Test class"); }
}
public class Q2 extends Test {
static void show1() {
System.out.println("Show1 in Q2 class"); }
void show2() {
System.out.println("Show2 in Q2 class"); }
public static void main(String[] args) {

Test t = new Q2();
t.show1();
t.show2();
}
}
 
Bojan Knezovic
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kathy,
static methods are never overrided. It's simple as that.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although this looks like method overriding, it is not. As was said previously, static methods can not be overridden - rather, they are hidden. Hidden methods and overridden methods behave very differently.
Be sure to check out the JLS, §8.4.6 Inheritance, Overriding, and Hiding for details.
 
Kathy Cai
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic