Concept of inheritance

In Inheritance, I have a static method in a superclass, and I inherit this class from one subclass. In this case, is the static method inherited to the subclass or not?

0
source share
7 answers

If this method is public or static in the superclass, it will be available in the subclass. Thus, in this sense he is inherited. The code below will compile and work 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 poor use of the term “inherited”, as it is not tied to a specific instance, is therefore Caleb’s answer. The normal OO design does not consider static methods as inherited, and it becomes very confusing, especially when you start talking about overriding them.

+1
source

Remember that static methods are not instance methods - they refer to the class, not to the instance. Since a derived class can be considered a base class, you can access the static method through a derived type.

Given:

 class A { public static void foo(){} } class B extends A { } 

Then:

 B.foo(); // this is valid 
+8
source

Wait, I'm standing fixed - static methods are inherited. Like. However, they do not act as the actual inheritance of the TOE. 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 will use Parent.printIt() because child1 has been added to the Parent class. If you call child2.printIt() , however, it will use Child.printIt() because it is passed to the child. So this is not really true inheritance, because redefinition does not stick if you drop the supertype. So this is not true polymorphism.

+2
source

Inherited in the sense that it can be accessed as a static method of any subclass

Why didn’t you try it yourself?

  • Create class A with staticMethod()
  • Create class B extends A
  • Try calling the static method with B.staticMethod()
+2
source

The parent static method will be available in the subclass, but cannot be overridden.

0
source

Yes, you can inherit static methods. But if your static method has a private access modifier, you cannot inherit it.

0
source

Another (advanced) concept that you probably care about here is the concept of "late static binding" - overriding static functions in child classes. Here's a question about this from the world of PHP, but it applies in all directions: When do you need to use late static binding?

0
source

All Articles