顾名思义,内部类就是这个类的内部定义的另一个类,这个类也叫外部类。
格式如下:
//外部类开始
标识符 class 外部类的名称 {
// 外部类的成员
//内部类开始
标识符 class 内部类的名称 外部类 {
// 内部类的成员 内部类
}
//内部类结束
}
//外部类结束
1、外部类声明的属性可以被内部类所访问
class Outer {
int score = 95;
void inst() {
Inner in = new Inner();
in.display();
}
class Inner {
void display() {
System.out.println(" 成绩: score = " + score);
}
}
}
public class InnerClassDemo {
public static void main(String[] args) {
Outer outer = new Outer();
outer.inst();
}
}
/*
输出结果:
成绩: score = 95
*/
2、内部类声明的属性不能被外部类所访问
class Outer {
int score = 95;
void inst() {
Inner in = new Inner();
in.display();
}
public class Inner {
void display() {
// 在内部类中声明一 name 属性
String name = " 张三";
System.out.println("成绩: score = " + score);
}
}
public void print() {
// 在此调用内部类的 name 属性
System.out.println(" 姓名:" + name);
}
}
public class InnerClassDemo {
public static void main(String[] args) {
Outer outer = new Outer();
outer.inst();
}
}
/*
编译结果:
InnerClassDemo.java:19: cannot resolve symbol symbol : variable name location: class Outer
System.out.println(" 姓名:" + name) ;
^
1 error
*/
3、static声明的内部类无法访问外部类中的非 static 类型的属性
class Outer {
int score = 95;
void inst() {
Inner in = new Inner();
in.display();
}
// 这里用 static 声明内部类
static class Inner {
void display() {
System.out.println("成绩: score = " + score);
}
}
}
public class InnerClassDemo {
public static void main(String[] args) {
Outer outer = new Outer();
outer.inst();
}
}
/*
编译结果:
InnerClassDemo.java:14: non-static variable score cannot be referenced from a static context
System.out.println(" 成绩: score = " + score);
^
1 error
*/
4、内部类也可以通过创建对象从外部类之外被调用,只要将内部类声明为 public 即可
class Outer {
int score = 95;
void inst() {
Inner in = new Inner();
in.display();
}
public class Inner {
void display() {
System.out.println("成绩: score = " + score);
}
}
}
public class InnerClassDemo {
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}
/*
输出结果:
成绩: score = 95
*/
5、内部类不仅可以在类中定义,也可以在方法中定义内部类
class Outer {
int score = 95;
void inst() {
class Inner {
void display() {
System.out.println(" 成绩: score = " + score);
}
}
Inner in = new Inner();
in.display();
}
}
public class InnerClassDemo {
public static void main(String[] args) {
Outer outer = new Outer();
outer.inst();
}
}
/*
输出结果:
成绩: score = 95
*/
6、在方法中定义的内部类只能访问方法中的 final 类型的局部变量
class Outer {
int score = 95;
void inst(final int s) {
int temp = 20;
class Inner {
void display() {
System.out.println(" 成绩: score = " + (score + s + temp));
}
}
Inner in = new Inner();
in.display();
}
}
public class InnerClassDemo {
public static void main(String[] args) {
Outer outer = new Outer();
outer.inst(5);
}
}
/*
编译结果:
InnerClassDemo.java:8: local variable temp is accessed from within inner class; needs to be declared final
System.out.println(" 绩 成 绩 : score = " + (score + s + temp));
^
1 error
由编译结果可以发现,内部类可以访问用 final 标记的变量 s,却无法访问在方法
内声明的变量 temp,所以只要将第 6 行的变量声明时,加上一个 final 修饰即可:
final int temp = 20 ;
*/
Comments | NOTHING