简体   繁体   中英

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!

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; eg

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.

如果您有权访问超类,那么您是否只是将有问题的方法设为私有?

由于静态方法基本上是可以在任何地方使用的浮动代码,因此将方法移至另一个(实用程序)类

覆盖签名不执行任何操作。

  1. If you want your method is only accessable to your parent class you have to make your method as private
  2. If the method has to limit access with in a package you have to make it as defaul(No Access modifiers ) Eg:

      void hello(){ } 

    Even if a sub class cannot access this method Outside the package (But keep in mind that a subclass in same package can access this method )

Hope this helps .....

If you do not want your sub-class to inherit any of the methods of the super-class,make the method in super-class private .

For example

Class Parent{

private void foo(){

}

}

class Child extends Parent{

}

In this scenario as the visibility level is private, the child class would not even have the visibility on the existence of a method named foo() in super class as it never had been inherited.

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