一,内部类可以访问外部类的私有属性及方法,同样外部类也可以很轻松地访问内部类的私有属性
package 类与对象;
class Outer
{
private String mes = "hello";
class Inner
{
private String mes2 = "world";
public void print()
{
System.out.println("内部类访问外部类的私有属性:"+mes);
// System.out.println("内部类访问外部类的私有属性:"+Outer.this.mes);
//如果用this,需要加上当前对象所属的类名即变成Outer.this
}
}
public void fun()
{
new Inner().print();
System.out.println("外部类访问内部类的私有属性:"+new Inner().mes2);
}
}
public class DEMO1 {
public static void main(String[] args) {
Outer out = new Outer();
out.fun();
}
}
二,上述通过fun()函数来调用内部类的print()方法,内部类能否实例化一个对象直接调用print()方法?
package 类与对象;
class Outer
{
private String mes = "hello";
class Inner
{
private String mes2 = "world";
public void print()
{
System.out.println("内部类访问外部类的私有属性:"+Outer.this.mes);
}
}
}
public class DEMO1 {
public static void main(String[] args) {
Outer.Inner in = new Outer().new Inner();
//产生内部类对象in
in.print();
}
}
三,static定义内部类,相当于产生了一个新的外部类,只有内部类才能用static定义,外部类不能用
package 类与对象;
class Outer
{
private static String mes = "hello";
static class Inner
{
private String mes2 = "world";
public void print()
{
System.out.println("内部类访问外部类的私有属性:"+mes);
}
}
}
public class DEMO1 {
public static void main(String[] args) {
Outer.Inner in = new Outer.Inner();//此时可以吧Outer.Inner看成一个新的外部类
//产生内部类对象in
in.print();
}
}
四,内部类定义在方法中,可以调用方法中的参数及局部变量
package 类与对象;
class Outer
{
public void fun(int temp) {
int temp1 = 100;
class Inner {
public void print() {
System.out.println("fun()中的参数temp = " + temp);
System.out.println("fun()中的局部变量temp1 = " + temp1);
}
}
new Inner().print();
}
}
public class DEMO1 {
public static void main(String[] args) {
Outer out = new Outer();
out.fun(100);
}
}
在jdk1.8及其以后在方法中定义内部类,当内部类调用该方法的参数及局部变量时,参数与变量声明时可以不加final。如果是jdk1.8之前的版本需要加final!