非静态内部类
package com.leo.demo;
/**
* @author java
*/
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}
/**
* @author java
*/
public class MyMainClass {
public static void main(String[] args) {
/**由于内部类嵌套在外部类中,必须先实例化外部类,然后创建内部类的对象类实现**/
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println("外部类变量" + myOuter.x + " 内部类变量:" + myInner.y);
}
}
私有内部类
package com.leo.demo;
/**
* @author java
*/
class OuterClass {
int x = 10;
/**内部类可以使用protected或private修饰,如果不希望内部类被外部类访问可以使用private修饰符**/
private class InnerClass {
int y = 5;
}
}
/**
* @author java
*/
public class MyMainClass {
public static void main(String[] args) {
/**由于内部类嵌套在外部类中,必须先实例化外部类,然后创建内部类的对象类实现**/
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println("外部类变量" + myOuter.x + " 内部类变量:" + myInner.y);
}
}
静态内部类
package com.leo.demo;
/**
* @author java
*/
class OuterClass {
int x = 10;
/**静态内部类用static关键字定义**/
static class InnerClass {
int y = 5;
}
}
/**
* @author java
*/
public class MyMainClass {
public static void main(String[] args) {
/**不需要创建外部类来访问,可以直接访问**/
OuterClass.InnerClass myInner = new OuterClass.InnerClass();
System.out.println(myInner.y);
}
}
内部类访问外部类
package com.leo.demo;
/**
* @author java
*/
class OuterClass {
int x = 10;
class InnerClass {
public int innerMethod() {
return x;
}
}
}
/**
* @author java
*/
public class MyMainClass {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new InnerClass();
System.out.println(myInner.innerMethod());
}
}