Inheritance vs Static in Java

后端 未结 6 1901
温柔的废话
温柔的废话 2020-12-06 15:17

I dont quite understand why Static methods can be inherited in Java ?

Inheritance is like inheriting from the base class AND Static belongs to the Class and not Obje

6条回答
  •  渐次进展
    2020-12-06 15:52

    If B is a subclass of A and we have A a = new B(); as a legal statement hence they are the same type and if the static method is on A then B will have it since they are of the same type in that regard. I think your confusion lies with the fact that static methods can be referenced via this making it seem as if they are inherited.

    It is bad practice to dispatch a static method via an instance of the class so it should always be A.staticMethod() which also clears up the inheritance misconception you have as B.staticMethod() would not refer to the same method as A if hidden/overriden.

提交回复
热议问题