Java puzzle: modifiers

Could you tell me 1) why you can make the constructor public for a class with a visible package? For instance:

class TestModifiers {
    public TestModifiers() {

    }
}

This class cannot be instantiated everywhere, but in the same package. So is this not enough to use the visible package modifier for the constructor? This is true for any method (public) in such a class (visible package)

2) let's say in the inner class I created two private variables . Why can I see them from the outer class? Isn't that weird? For instance:

class A {
  A(){}

  class B {
    private int b1;
    private int b2;
  }

  public static void main(String[] args) {
   new B().b1 = 1;
   new B().b2 = 2;
  }
 } 
+3
source share
4 answers

no, , , , . - , , .

, , , :

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!");
    }
}

mypackage MyRunnable ( Runnable) :

Runnable r = Surprises.getSurprise();
r.run();

, .

+5

, , , . .

abstract class MyBaseClass {
  public abstract void method();
}

public class MySubClass extends MyBaseClass {
  @Override public void method() { ... }
}

, , , .

+1
  • .
  • class B, B.b1,b2 A, A.
+1

1), ?

, .

, , , , , 45 ( ).


Unable to answer your second question. I also think this is strange.

-1
source

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


All Articles