简体   繁体   中英

Static method in parent class does not allow child to add a non static method?

The below code does not compile:

public class Child extends Parent{

    void foo() {        
    }
}

 class Parent{
    public static void foo(){}
}

Why can't I declare a non static method in my child class? Overriding is not allowed in this case as the method is static, so why is the compiler not allowing us to declare an instance method?

Because Child Classes inherent all methods and fields from the Parent Class. In this case there will be two Child#foo() methods in the Child class since it would not have been overridden if this had had compiled.

That method has the same signature as the static method, and since you can't override static methods (and it is still a part of Parent , which Child still gets), you can't declare another foo with the same signature in a child method.

To be more technical, the JLS specifies :

It is a compile-time error for the body of a class to declare as members two methods with override-equivalent signatures (§8.4.2).

If you changed the signature; that is, if you declared an argument in the child class' method, then it would be okay.

You can't change access of inherited methods while overriding them - static stays static. Same thing applies when overloading methods in single class - you can use same method name but methods need to accept different parameters.

Because the child recognize foo() from parent and itself. So you can't not create with your current code. However, you can declare new foo() in your child like this:

public class Child extends Parent{


   public static void foo() {   
    }
}

 class Parent{
    public static void foo(){
    }
}

More detail here: You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it . http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM