Are static methods inherited in Java?
Asked Answered
I

15

172

I was reading A Programmer’s Guide to Java™ SCJP Certification by Khalid Mughal.

In the Inheritance chapter, it explains that

Inheritance of members is closely tied to their declared accessibility. If a superclass member is accessible by its simple name in the subclass (without the use of any extra syntax like super), that member is considered inherited

It also mentions that static methods are not inherited. But the code below is perfectlly fine:

class A
{
    public static void display()
    {
        System.out.println("Inside static method of superclass");
    }
}

class B extends A
{
    public void show()
    {
        // This works - accessing display() by its simple name -
        // meaning it is inherited according to the book.
        display();
    }
}

How am I able to directly use display() in class B? Even more, B.display() also works.

Does the book's explanation only apply to instance methods?

Intrauterine answered 24/4, 2012 at 5:0 Comment(3)
#4716540 has interesting info.Rally
That's not what it says in my copy, 1st edition. Please provide an actual quotation.Tadeo
related: #25169675Hostel
P
216

All methods that are accessible are inherited by subclasses.

From the Sun Java Tutorials:

A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members

The only difference with inherited static (class) methods and inherited non-static (instance) methods is that when you write a new static method with the same signature, the old static method is just hidden, not overridden.

From the page on the difference between overriding and hiding.

The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass

Poverty answered 24/4, 2012 at 5:11 Comment(7)
so inherited relates to whether we can override that member in subclass?Intrauterine
Well, that is part of inheritance, but not all of it. I would say the other major parts of inheritance is code reuse and polymorphism.Poverty
Does redefining also has some rules like overriding has?Outdo
@Intrauterine no not exactly. All the things your subclass see further up in the hierarchy, is stuff that your class inherited. But static methods which is inherited, cannot be overridden, only hidden ("redeclared" with the same signature). Therefore, you may also declare your static methods as final, it doesn't matter. Which static method that will be invoked is known at compile time. With non-final instance methods, the resolution must be deferred to runtime as they may be overridden.Creaky
Your last paragraph is completely undermined !!! "The version of the overriden method that gets invoked is the one in the subclass" this is not true : Let's say : The version of the overriden method that gets invoked is only determined in the runtime by the JVM related to which object has made the call :)Externality
As a side note, static methods in interface are not "inherited". Even in a class implementing this interface, one has to explicitly specify the interface name to reference the static methods.Metalinguistics
it is interesting that static methods in interface are NOT inherited!Ludovick
A
29

You can experience the difference in following code, which is slightly modification over your code.

class A {
    public static void display() {
        System.out.println("Inside static method of superclass");
    }
}

class B extends A {
    public void show() {
        display();
    }

    public static void display() {
        System.out.println("Inside static method of this class");
    }
}

public class Test {
    public static void main(String[] args) {
        B b = new B();
        // prints: Inside static method of this class
        b.display();

        A a = new B();
        // prints: Inside static method of superclass
        a.display();
    }
}

This is due to static methods are class methods.

A.display() and B.display() will call method of their respective classes.

Ainslie answered 21/11, 2014 at 5:47 Comment(4)
Invoking a static method on an instance like you're trying to will not work in java.Klaraklarika
Thats what this program explains, instantiating object of B and expecting inheritance to work will not be possible with static members. Try taking same code in your eclipse/any ide or compile using javac and execute itAinslie
@LucasC.Feijo actually I it does work. At least in my IDE (eclipse). I just get a warning. It might not be good style though... but that's a different story.Questionnaire
@LucasC.Feijo call a static method on an instance is not recommended. But it works the same as calling a static method on a class name.Eurus
I
24

Static methods in Java are inherited, but can not be overridden. If you declare the same method in a subclass, you hide the superclass method instead of overriding it. Static methods are not polymorphic. At the compile time, the static method will be statically linked.

Example:

public class Writer {
    public static void write() {
        System.out.println("Writing");
    }
}

public class Author extends Writer {
    public static void write() {
        System.out.println("Writing book");
    }
}

public class Programmer extends Writer {

    public static void write() {
        System.out.println("Writing code");
    }

    public static void main(String[] args) {
        Writer w = new Programmer();
        w.write();

        Writer secondWriter = new Author();
        secondWriter.write();

        Writer thirdWriter = null;
        thirdWriter.write();

        Author firstAuthor = new Author();
        firstAuthor.write();
    }
}

You'll get the following:

Writing
Writing
Writing
Writing book
Illinois answered 27/7, 2018 at 4:33 Comment(2)
Third example is amazing: Writer thirdWriter = null; thirdWriter.write(); it returns value! Now I see that I don't know enough .. xDOchlophobia
Best answer for this post.Fining
T
14

If that's what the book really says, it's wrong.[1]

The Java Language Specification #8.4.8 states:

8.4.8 Inheritance, Overriding, and Hiding

A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass for which all of the following are true:

  • m is a member of the direct superclass of C.

  • m is public, protected, or declared with package access in the same package as C.

  • No method declared in C has a signature that is a subsignature (§8.4.2) of the signature of m.

[1] It doesn't say that in my copy, 1st edition, 2000.

Tadeo answered 19/4, 2015 at 3:43 Comment(0)
H
5

B.display() works because static declaration makes the method/member to belong to the class, and not any particular class instance (aka Object). You can read more about it here.

Another thing to note is that you cannot override a static method, you can have your sub class declare a static method with the same signature, but its behavior may be different than what you'd expect. This is probably the reason why it is not considered inherited. You can check out the problematic scenario and the explanation here.

Heath answered 24/4, 2012 at 5:12 Comment(0)
G
3

Static methods are inherited in Java but they don't take part in polymorphism. If we attempt to override the static methods they will just hide the superclass static methods instead of overriding them.

Gillam answered 24/6, 2014 at 10:39 Comment(1)
I don't see a reason for downvoting this answer. It is crisp & clear, at least the first part. The second part shouldn't be taken too technically, otherwise its okay. To clarify, in overriding methods the return type can change (to sub-type) whereas this isn't the case with static methods. Technically 'attempt to override' doesn't apply to static methods, so all we can say is that we cannot.Ats
M
3

This concept is not that easy as it looks. We can access static members without inheritance, which is HasA-relation. We can access static members by extending the parent class also. That doesn't imply that it is an ISA-relation (Inheritance). Actually static members belong to the class, and static is not an access modifier. As long as the access modifiers permit to access the static members we can use them in other classes. Like if it is public then it will be accessible inside the same package and also outside the package. For private we can't use it anywhere. For default, we can use it only within the package. But for protected we have to extend the super class. So getting the static method to other class does not depend on being Static. It depends on Access modifiers. So, in my opinion, Static members can access if the access modifiers permit. Otherwise, we can use them like we use by Hasa-relation. And has a relation is not inheritance. Again we can not override the static method. If we can use other method but cant override it, then it is HasA-relation. If we can't override them it won't be inheritance.So the writer was 100% correct.

Mal answered 27/9, 2017 at 20:55 Comment(1)
Extending the parent class is an 'is-a' relationship. If the access is private you can use it from within the class. 'protected' includes derived classes and classes in the current package. Too many errors here.Tadeo
F
1

Static methods in class are inherited while static methods in interface aren't inherited.

Static methods in class can be invoked using instance while static methods in interface can be invoked only through interface name as they aren't inherited

Foramen answered 2/3, 2022 at 13:21 Comment(1)
Your answer is halfway there, but it could be more helpful by pointing out what is wrong with the question posted. It is wrong to talk about inheritance when it comes to static methods, because they are not related to an instance. They are pure functions that are only associated with a class to give them a home. Because they are not related to any instances, they can of course not access the state of any instance, only static data.Interlink
B
0

All the public and protected members can be inherited from any class while the default or package members can also be inherited from the class within the same package as that of the superclass. It does not depend whether it is static or non static member.

But it is also true that static member function do not take part in dynamic binding. If the signature of that static method is same in both parent and child class then concept of Shadowing applies, not polymorphism.

Beuthen answered 26/7, 2014 at 5:3 Comment(0)
N
0

Static method is inherited in subclass but it is not polymorphism. When you writing the implementation of static method, the parent's class method is over hidden, not overridden. Think, if it is not inherited then how you can be able to access without classname.staticMethodname();?

Nylon answered 7/9, 2014 at 11:1 Comment(0)
G
0

You can override static methods, but if you try to use polymorphism, then they work according to class scope(Contrary to what we normally expect).

public class A {

    public static void display(){
        System.out.println("in static method of A");
    }
}

public class B extends A {

    void show(){
        display();
    }

     public static void display(){
        System.out.println("in static method of B");
    }

}
public class Test {

    public static void main(String[] args){
        B obj =new B();
        obj.show();

        A a_obj=new B();
        a_obj.display();


    }


}

IN first case, o/p is the "in static method of B" # successful override In 2nd case, o/p is "in static method of A" # Static method - will not consider polymorphism

Gruchot answered 6/5, 2015 at 6:32 Comment(0)
H
-1

We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism.Because since all static members of a class are loaded at the time of class loading so it decide at compile time(overriding at run time) Hence the answer is ‘No’.

Homely answered 4/4, 2016 at 2:24 Comment(2)
I don't know why people always down-vote and not give the reason of down-voting.Manila
This answer is about overriding. The question is about inheritance.Tadeo
M
-1

Many have voiced out their answer in words. This is an extended explanation in codes:

public class A {
    public static void test() {
        System.out.println("A");
    }
    public static void test2() {
        System.out.println("Test");
    }
}

public class B extends A {
    public static void test() {
        System.out.println("B");
    }
}

// Called statically
A.test();
B.test();
System.out.println();

// Called statically, testing static inheritance
A.test2();
B.test2();
System.out.println();

// Called via instance object
A a = new A();
B b = new B();
a.test();
b.test();
System.out.println();

// Testing inheritance via instance call
a.test2();
b.test2();
System.out.println();

// Testing whether calling static method via instance object is dependent on compile or runtime type
((A) b).hi();
System.out.println();

// Testing whether null instance works
A nullObj = null;
nullObj.hi();

Results:

A
B

Test
Test

A
B

Test
Test

A

A

Therefore, this is the conclusion:

  1. When we call the static in a static manner via ., it will look for the static defined in that class, or the class nearest to that in the inheritance chain. This proves that static methods are inherited.
  2. When static method is called from an instance, it calls the static method defined in the compile-time type.
  3. Static method can be called from a null instance. My guess is that the compiler will use the variable type to find the class during compilation, and translate that to the appropriate static method call.
Mammalian answered 9/2, 2018 at 3:29 Comment(1)
Mere code is not an explanation, it is a demonstration. An answer to this question should cite normative references, not just exhibit the behaviour of some unstated implementation.Tadeo
D
-2

Static members are universal members. They can be accessed from anywhere.

Doradorado answered 8/9, 2013 at 15:46 Comment(5)
can be accessed from anywhere taken literally, that is wrong: static != scope. you might want to clarify :-)Inconsequent
Actually, this answer is fine when taken literally. I can't think of a single place in code where code can go that one cannot access a static member of class. You can access them in static initializers, static constructors, instance constructors, methods, properties, in different classes, in any scope. As long as the class and static method are public, they can be accessed from anywhere, assuming there are no circular dependencies on the static initializers. In essence, static members are not inherited, they are just class-level (i.e. universal) methods that are accessible from anywhere.Vanettavang
@Vanettavang The answer is wrong in the case of methods that are private, or package-protected accessed from outside the package.Tadeo
@Inconsequent - off topic. java swing ? do people actually use that these days ?Soni
@Doradorado try calling private static from outside the class. It won't work.Larrikin
P
-3

Static members will not be inherited to subclass because inheritance is only for non-static members.. And static members will be loaded inside static pool by class loader. Inheritance is only for those members which are loaded inside the object

Promotive answered 16/1, 2016 at 6:52 Comment(2)
Completely incorrect. See JLS #8.4.8.Tadeo
incorrect, please update your answer if you are clear now :)Coumarin

© 2022 - 2024 — McMap. All rights reserved.