Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a subclass inherit a static method in the super class

Considering some security issues, I don't want the subclass inherit the static method from its super class,not even call this method, how can I do this? Please help!

like image 710
Ivy Avatar asked Dec 03 '25 17:12

Ivy


1 Answers

Static methods are not inherited in the same sense as instance methods are. If you declare a static method as public (or package private) it is accessible whether or not there is a local redeclaration in a child class. The local redeclaration merely means that the child class has to qualify the name of the method; e.g.

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

public class Child {
    public static void foo() { ... }
    public static void main(String[] args) {
        foo();  // calls local override
        Parent.foo(); // calls original version.
}

If you don't want the Child class to be able to call the Parent.foo method, then you need to declare it as private (or maybe package private if Child and Parent are in different packages.)

But even then, if the Child class has permission to use reflection, then it can easily use that to call a private method in the Parent class. So unless you are sandboxing your code Java access modifiers are not a security mechanism.

like image 77
Stephen C Avatar answered Dec 06 '25 08:12

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!