of the classes they are nested within
class MyClass {
private void f() {}
class A {
private void g() {}
public class B {
void h() {
g();
f();
}
}
}
}
public class MainClass {
public static void main(String[] args) {
MyClass a = new MyClass();
MyClass.A innerA = a.new A();
MyClass.A.B innerb = innerA.new B();
innerb.h();
}
}
Proper inheritance of an inner class.
class A {
protected class InnerA {
public InnerA() {
System.out.println("A.InnerA()");
}
public void f() {
System.out.println("A.InnerA.f()");
}
}
private InnerA y = new InnerA();
public A() {
System.out.println("New A()");
}
public void insertYolk(InnerA yy) {
y = yy;
}
public void g() {
y.f();
}
}
class B extends A {
public class InnerB extends A.InnerA {
public InnerB() {
System.out.println("B.InnerB()");
}
public void f() {
System.out.println("B.InnerB.f()");
}
}
public B() {
insertYolk(new InnerB());
}
}
public class MainClass {
public static void main(String[] args) {
A e2 = new B();
e2.g();
}
}
output
A.InnerA() New A() A.InnerA() B.InnerB() B.InnerB.f()
Using inner classes for callbacks
interface InterfaceA {
void increment();
}
class ClassA implements InterfaceA {
private int i = 0;
public void increment() {
i++;
System.out.println(i);
}
}
class ClassB {
void increment() {
System.out.println("Other operation");
}
static void f(ClassB mi) {
mi.increment();
}
}
class ClassC extends ClassB {
private int i = 0;
private void incr() {
i++;
System.out.println(i);
}
private class Closure implements InterfaceA {
public void increment() {
incr();
}
}
InterfaceA getCallbackReference() {
return new Closure();
}
}
class Caller {
private InterfaceA callbackReference;
Caller(InterfaceA cbh) {
callbackReference = cbh;
}
void go() {
callbackReference.increment();
}
}
public class MainClass {
public static void main(String[] args) {
ClassA c1 = new ClassA();
ClassC c2 = new ClassC();
ClassB.f(c2);
Caller caller1 = new Caller(c1);
Caller caller2 = new Caller(c2.getCallbackReference());
caller1.go();
caller1.go();
caller2.go();
caller2.go();
}
}
Returning a reference to an inner class
class MyClass {
private class ClassB implements B {
private int i = 11;
public int value() {
return i;
}
}
protected class ClassA implements A {
private String label;
private ClassA(String whereTo) {
label = whereTo;
}
public String readLabel() {
return label;
}
}
public A dest(String s) {
return new ClassA(s);
}
public B cont() {
return new ClassB();
}
}
public class MainClass {
public static void main(String[] args) {
MyClass p = new MyClass();
B c = p.cont();
A d = p.dest("A");
}
}
interface B {
int value();
}
interface A {
String readLabel();
}
No comments:
Post a Comment