C ++ as protected in java

Possible duplicate:
How to make data member access only available for class and subclass

In java,
protected members can be accessed from a class, its subclasses, and from all classes present in one package,
but I want the member to be accessible only from the class and its subclasses (as well as the protected member in C ++).

eg:

class A { protected void fun() { System.out.println("Hello"); } } class B { public static void main(String args[]) { A a = new A(); a.fun(); } } 

here, the fun () function is available for B, even if B is not a subclass of A.

How to make A inaccessible to all classes that are not a subclass of A?

edit :: I want to achieve this in java.

+6
source share
3 answers

There is no way to do this in Java.

However, you (ideally) control all the code in your package, so you just need to make sure that you are not using it yourself.

+8
source

In Java, secure tools are "accessible by successors and others in one package."

In C ++, protected means "inherited."

They are not really equivalent due to the availability of the package in Java.

The only way you can imitate C ++ - security in Java - is to declare classes in their own package, but I do not recommend this.

+2
source

There is no way to do this in java. A protected facility that is visible to descendants and classes within the same package. But you can seal your package ( http://docs.oracle.com/javase/tutorial/deployment/jar/sealman.html ) so that no one can create new classes in your package.

+2
source

Source: https://habr.com/ru/post/917191/


All Articles