Ich kann hier nicht herausfinden, um welche Art von Alias es sich bei der var tatsächlich handelt:
- ist es „Child.InnerChild“? Wäre das nicht eine Typinkongruenz?
- „InnerParent“? Umgeht dies nicht die geschützte Zugriffsbeschränkung?
Code: Select all
public abstract class Parent {
protected abstract static class InnerParent {
public InnerParent self() {
return this;
}
}
}
Code: Select all
public class Child extends Parent {
public static class InnerChild extends InnerParent {}
}
Code: Select all
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());
}
}
Warum var funktioniert
[*]Abgeleiteter Typ: Der abgeleitete Typ für var innerChild ist Parent.InnerParent.
[*]Zugriffsregeln: Da der Typ abgeleitet und nicht explizit in den Code geschrieben wird, erzwingt der Compiler keine Zugriffsbeschränkungen für die deklarierte Variable.
< /ul>
Ich habe ein neues Problem gefunden: Warum kann ich nicht auf getClass() zugreifen?
< img alt="Zugriff auf getClass()-Problem nicht möglich" src="https://i.sstatic.net/gYAxY4dI.png" />
Es ist jedoch möglich, auf diese Weise zu kompilieren.
Code: Select all
System.out.println(((Object) innerChild).getClass().getName());
// OUTPUT: com.github.lorenzoyang.anotherpackage.Child$InnerChild