Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Another hiding vs overriding question

 
Dave Reinhardt
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Parent {
static void get1() {
System.out.print("Parent get1 ");
}
void get2() {
System.out.print("Parent get2 ");
}
public void get() {
get1();
get2();
}
}
public class Child extends Parent {
static void get1() {
System.out.print("Child get1 ");
}
void get2() {
System.out.print("Child get2 ");
}
public static void main(String[] args) {
(new Child()).get();
}

}
The output is: Parent get1 Child get2

The explaination I have is that get1() in the Parent class is determined at compile time, but I could use a better explaination for this behavior. Given that static methods are not inherited, why does it allow the instance get() method to be inherited in Child when it contains a static method. I would have thought this would not be allowed.
 
Gowher Naik
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static methods are not inherited but they can be redefine in child class.
but that redefined static method is associated with class in which it is defined only.
In your code get() method is not static hence it will be inherited
by child class.What method conatins does not matter but what method is
matters i.e in parent classes get() method is not static hence it will be inherited by child class.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where are you getting the idea that static methods are not inherited?

How does main in A42 get to access method m() in B42 if it is not inherited?


[ September 02, 2006: Message edited by: Barry Gaunt ]
 
Dave Reinhardt
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, I did not know that, and I'm not sure where I got the idea that you couldn't access the super class's static methods from the sub class. I tested the code and was able to access the super class's static method from within the sub class using:
1. sub class name
2. super class name
3. sub class instance //with warning

Is it possible that some people define inheritance to be directly tied to polymorphism? Because clearly there is no polymorphic behavior with static methods or fields.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic