public class MainClass {
private void method(boolean b) {
if (b) {
class A {
private String id;
A(String s) {
id = s;
}
String getSlip() {
return id;
}
}
A ts = new A("slip");
String s = ts.getSlip();
}
// Can't use it here! Out of scope:
// ! A ts = new A("x");
}
public void track() {
method(true);
}
public static void main(String[] args) {
MainClass p = new MainClass();
p.track();
}
}
Nested classes (static inner classes)
public class MainClass {
private static class ClassA implements A {
private int i = 11;
public int value() {
return i;
}
}
protected static class ClassB implements B {
private String label;
private ClassB(String whereTo) {
label = whereTo;
}
public String readLabel() {
return label;
}
// Nested classes can contain other static elements:
public static void f() {
}
static int x = 10;
static class InnerInnerClass {
public static void f() {
}
static int x = 10;
}
}
public static B dest(String s) {
return new ClassB(s);
}
public static A cont() {
return new ClassA();
}
public static void main(String[] args) {
A c = cont();
B d = dest("A");
}
}
interface A {
int value();
}
interface B {
String readLabel();
}
An inner class cannot be overriden like a method
class A {
private InnerA y;
protected class InnerA {
public InnerA() { System.out.println("A.InnerA()"); }
}
public A() {
System.out.println("New A()");
y = new InnerA();
}
}
class B extends A {
public class InnerB {
public InnerB() { System.out.println("B.InnerB()"); }
}
}
public class MainClass{
public static void main(String[] args) {
new B();
}
}
Two ways that a class can implement multiple interfaces
interface A {
}
interface B {
}
class X implements A, B {
}
class Y implements A {
B makeB() {
// Anonymous inner class:
return new B() {
};
}
}
public class MainClass {
static void takesA(A a) {
}
static void takesB(B b) {
}
public static void main(String[] args) {
X x = new X();
Y y = new Y();
takesA(x);
takesA(y);
takesB(x);
takesB(y.makeB());
}
}
No comments:
Post a Comment