Я не могу понять, какой тип псевдонима здесь на самом деле var:
Я не могу понять, какой тип псевдонима здесь на самом деле:
p>
- это «Child.InnerChild»? Не будет ли это несоответствием типов?
- "InnerParent"? Разве это не обходит ограничитель защищенного доступа?
public abstract class Parent {
protected abstract static class InnerParent {
public InnerParent self() {
return this;
}
}
}
public class Child extends Parent {
public static class InnerChild extends InnerParent {}
}
import anotherpackage.Child;
/**
* Compiling with Java 11:
*/
public class Main {
public static void main(String[] args) {
// As we expected a compilation error: The returned static type does not match the expected type
// Child.InnerChild innerChild = new Child.InnerChild().self();
// As we expected a compilation error: Parent.InnerParent is package visible (protected)
// Parent.InnerParent innerChild = new Child.InnerChild().self();
// Why does it compile and run correctly here?
// var is just syntactic sugar for the compiler type, it should be a Parent.InnerParent alias here,
// why is var allowed to transgress the protected access restriction?
var innerChild = new Child.InnerChild().self(); // perhce' non da' errore ? var e' un alias di cosa ?
System.out.println(innerChild);
System.out.println(innerChild.getClass().getName());
}
}
Я также задал вопрос ChatGPT, но он не отвечает так, как мне хотелось бы, и я не уверен, что это правильно:
Почему var работает
- Выводимый тип: Выведенный тип для var innerChild есть Parent.InnerParent.
- Правила доступа: поскольку тип выводится, а не прописывается явно в коде, компилятор не применяет ограничения доступа. для объявленной переменной.

Однако можно скомпилировать и таким образом.System.out.println(((Object) innerChild).getClass().getName());
// OUTPUT: com.github.lorenzoyang.anotherpackage.Child$InnerChild
Подробнее здесь: https://stackoverflow.com/questions/793 ... estriction