Java Puzzle: modifiers
Can you, please, tell me 1) why it is possible to assign a constructor as public for a package-visible class? For example:
class TestModifiers {
public TestModifiers() {
}
}
This class can't be instantiated everywhere but in the same package. So that isn't it enough to use a package-visible modifier for a constructor? That is also true with any method(public) in such a class(package-visible)
2) say, in an inner class I have created two private variables. Why can I see them from the outer class? Isn't it strange?? For example:
class A {
A(){开发者_如何学Python}
class B {
private int b1;
private int b2;
}
public static void main(String[] args) {
new B().b1 = 1;
new B().b2 = 2;
}
}
There is no value in a non-public class having a public constructor since, as you rightly state, the class isn't accessible outside of that scope. It will compile - that's just the way things are - but many code analysis tools will generate a warning.
There is value in a non-public class having public methods if the class extends or implements a public class or interface, since the derived class can stand in for the base class or interface type:
package mypackage;
class MyRunnable implements Runnable {
private final String message;
MyRunnable(String message) {
this.message = message;
}
@Override
public void run() {
System.out.println(this.message);
}
}
public class Surprises {
public static Runnable getSurprise() {
return new MyRunnable("boo!");
}
}
Code outside of mypackage
can then obtain a MyRunnable
instance (as a Runnable
) and call the public method:
Runnable r = Surprises.getSurprise();
r.run();
I'll ignore your second question since it was answered elsewhere in the comments.
Public modifiers are allowed on non-public classes because public methods defined in those classes may need to be overridden in public subclasses. E.g.
abstract class MyBaseClass {
public abstract void method();
}
public class MySubClass extends MyBaseClass {
@Override public void method() { ... }
}
Rather than impose a restriction on constructors that does not appear on other members, public constructors are allowed on classes regardless of the visibility of the containing classes.
- It may be useful for inheritance.
class B
,B.b1,b2
belongs to class A, they are inside A.
1) why it is possible to assign a constructor as public for a package-visible class?
It's much more convenient then it could be.
Just imagine that you have a public class, and then you understand that you can make it package-private, and after that compiler tells you that there's 45 errors (on every of your public methods).
Cannot reply on your second question. I also think that it's weird.
精彩评论