Verfahren Lokale innere Klasse
-
09-06-2019 - |
Frage
public class Test {
public static void main(String[] args) {
}
}
class Outer {
void aMethod() {
class MethodLocalInner {
void bMethod() {
System.out.println("Inside method-local bMethod");
}
}
}
}
Kann mir jemand sagen, wie die Nachricht von bMethod
drucken?
Lösung
Sie können nur MethodLocalInner
innerhalb aMethod
instanziiert. So tun
void aMethod() {
class MethodLocalInner {
void bMethod() {
System.out.println("Inside method-local bMethod");
}
}
MethodLocalInner foo = new MethodLocalInner(); // Default Constructor
foo.bMethod();
}
Andere Tipps
Innerhalb der Methode aMethod nach der Deklaration der Klasse MethodLocalInner Sie könnten zum Beispiel tun, den folgenden Aufruf:
new MethodLocalInner().bMethod();
Warum Sie nicht nur eine Instanz von MethodLocalInner
schaffen, in aMethod
und bMethod
auf die neue Instanz anrufen?
Dies könnte Ihnen den Einstieg, (ich habe nichts praktisch zu testen mit). Beachten Sie die modifizierte Konstruktor Syntax:
http://java.sun.com/docs /books/tutorial/java/javaOO/nested.html
Sie müssen neue Outer () aufzurufen. AMethod () in Ihrem Hauptverfahren. Sie müssen auch einen Verweis auf MethodLocalInner () bMethod () in Ihrem aMethod (), wie folgt hinzuzufügen:.
public class Test {
public static void main(String[] args) {
new Outer().aMethod();
}
}
void aMethod() {
class MethodLocalInner {
void bMethod() {
System.out.println("Inside method-local bMethod");
}
}
new MethodLocalInner().bMethod();
}