开发者

Inheritance concept

In Inheritance concept, i have a static method in super class and i am inheriting t开发者_运维百科hat class to one sub class. In that case the static method is inherited to sub class or not?


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


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?

  1. Create a class A with a staticMethod()
  2. Create a class B extends A
  3. Try calling the static method with B.staticMethod()


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.


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.


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: When would you need to use late static binding?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜