In Inheritance concept, i have a static method in super class and i am inheriting that class to one sub class. In that case the static method is inherited to sub class or not?
Wait, I stand corrected -- static methods ARE inherited. Sort of. However, they don't act like real OO inheritance. For example, with these classes:
public class Parent {
public static void printIt() {
System.out.println("I'm Parent!");
}
}
public class Child extends Parent {
public static void printIt() {
System.out.println("I'm Child!");
}
public static void main(String[] args) {
Parent child1 = new Child();
Child child2 = new Child();
child1.printIt();
child2.printIt();
}
}
If you call child1.printIt()
, it'll use Parent.printIt()
, because child1 has been cast to a Parent
class. If you call child2.printIt()
, however, it'll use Child.printIt()
, because it's cast to a child. So it's not really true inheritance, because overriding doesn't stick if you cast to a supertype. Thus it's not a true polymorphism.
It is inherited, in the sense that it can be accessed as a static method of any subclass
Why didn't you try it yourself?
- Create a
class A
with astaticMethod()
- Create a
class B extends A
- Try calling the static method with
B.staticMethod()
If the method is public static or protected static in the superclass it will be accessible in the subclass. So in that sense it is inherited. The code below will compile and run fine.
public class A {
public static String foo() {
return "hello world";
}
}
public class B extends A {
public void bar() {
System.out.println(foo());
}
}
However, this is a bad use of the term "inherited" as it is not tied to a particular instance - hence Kaleb's answer. Normal OO design does not treat static methods as inherited, and it gets very confusing, especially when you start talking about overriding them.
Remember that static methods are not instance methods - they relate to a class and not an instance. Since the derived class can be considered to be of the base type, you can access the static method via the derived type.
Given:
class A {
public static void foo(){}
}
class B extends A {
}
Then:
B.foo(); // this is valid
The parent static method will be accessible in subclass, but cannot be overriden.
Yes you can inherit static methods. But if your static method has private access modifier you can't inherit it
Another (advanced) concept that you would probably care about here is the concept of "late static binding" - overriding static functions in child classes. Here's a question on this from the PHP world, but it applies across the board: http://stackoverflow.com/questions/87192/when-would-you-need-to-use-late-static-binding/87351#87351