public class MainClass {
class A {
private int i = 11;
public int value() {
return i;
}
}
class B {
private String label;
B(String whereTo) {
label = whereTo;
}
String readLabel() {
return label;
}
}
public static void main(String[] args) {
MainClass p = new MainClass();
// Must use instance of outer class
// to create an instances of the inner class:
MainClass.A c = p.new A();
MainClass.B d = p.new B("A");
}
}
Nested Classes
class Outside {
public class Inside {
}
}
public class MainClass {
public static void main(String[] arg) {
Outside outer = new Outside();
Outside.Inside inner = outer.new Inside();
}
}
output
Nested Classes
Creating a new nested object outside
class Outside {
public class Inside {
}
public Outside() {
Inside inner = new Inside();
}
}
Static Nested Classes
public class Outside {
public static class Skinside {
}
public class Inside {
}
}
public class MainClass {
public static void main(String[] arg) {
Outside.Skinside example = new Outside.Skinside();
}
}
Creating inner classes
public class MainClass {
class A {
private int i = 11;
public int value() {
return i;
}
}
class B {
private String label;
B(String whereTo) {
label = whereTo;
}
String readLabel() {
return label;
}
}
// Using inner classes looks just like
// using any other class, within MainClass:
public void ship(String dest) {
A c = new A();
B d = new B(dest);
System.out.println(d.readLabel());
}
public static void main(String[] args) {
MainClass p = new MainClass();
p.ship("AAA");
}
}
Defining references to inner classes
public class MainClass {
class A {
private int i = 11;
public int value() {
return i;
}
}
class B {
private String label;
B(String whereTo) {
label = whereTo;
}
String readLabel() {
return label;
}
}
public B to(String s) {
return new B(s);
}
public A cont() {
return new A();
}
public void ship(String dest) {
A c = cont();
B d = to(dest);
System.out.println(d.readLabel());
}
public static void main(String[] args) {
MainClass p = new MainClass();
p.ship("A");
MainClass q = new MainClass();
MainClass.A c = q.cont();
MainClass.B d = q.to("A");
}
}
Nesting a class within a method
public class MainClass {
public A dest(String s) {
class B implements A {
private String label;
private B(String whereTo) {
label = whereTo;
}
public String readLabel() {
return label;
}
}
return new B(s);
}
public static void main(String[] args) {
MainClass p = new MainClass();
A d = p.dest("A");
}
}
interface A {
String readLabel();
}
No comments:
Post a Comment