局部内部类
1)局部内部类不能被public、static、private修饰
2)局部内部类不能在外部类中进行实例化
3)局部内部类访问方法中的变量时此变量需要final修饰
4)局部内部类能直接访问外部类的成员变量和方法
5)局部内部类只能在包含他的方法范围内进行实例化public class Family { public static void main(String[] args) { father father = new father(); father.func(); } } class father{ public int a; private int b; public static int c; public void func(){ int k=10; class Son{ public void ser(){ System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(k); } } Son son=new Son(); son.ser(); } }
实例内部类
1)实例内部类中不能定义静态成员变量和静态方法
2)若非要使用静态则添加final即可,如:public final static int x;因为常量是在编译时就已经确认好的。
3)内部类可以直接访问外部成员变量和方法,private修饰的也可调用
4)外部类不能直接访问内部类的成员变量和方法,需要实例化内部类才可访问。
class Father{
public int a=1;
private int b=2;
public static int c=3;
class Son{
//实例内部类
public final static int d=4;
public int e=5;
private int f=6;
public void func() {
System.out.println(a);//1
System.out.println(b);//2
System.out.println(c);//3
}
}
public void x(){
Son son=new Son();
System.out.println(Son.d);
System.out.println(son.e);
System.out.println(son.f);
}
}
为什么实例内部类不能使用静态成员变量呢?
因为静态成员变量是属于类的,不是属于方法的(这里我们将内部类想象成是一个方法更容易理解)。
那么如何进行实例化内部类的呢?
Father father=new Father();
Father.Son son= father.new Son();
同名情况下又该怎么处理呢?
若访问外部类成员:外部类名.this.相同名
静态内部类
1)静态内部类不能“直接”访问外部类成员变量和方法 。
2)可以直接调用外部类静态成员和方法,能够定义静态成员和方法。
3)若需要使用外部类成员变量和方法需要实例化外部类对象。
4)实例化外部类对象后,能够访问到private修饰的成员变量和方法。
class Father{
public int a=1;
private int b=2;
public static int c=3;
static class Son{
public static int d=4;
public int e=5;
private int f=6;
public void func() {
Father father=new Father();
System.out.println(father.a);//1
System.out.println(father.b);//2
System.out.println(c);//3
}
}
public void x(){
Son son=new Son();
System.out.println(Son.d);
System.out.println(son.e);
System.out.println(son.f);
}
}
静态内部类是如何实例化呢?
Father.Son son=new Father.Son();
静态内部类不需要要有外部类的对象才能实例化,因为它是静态的。
如果内部类成员和外部类成员名重名时我们该如何处理呢?
通过-> 实例化名.X调用
匿名内部类
interface run{
void running();
}
public class Family {
public static void main(String[] args) {
new run(){
public void running(){
System.out.println("哈哈哈");
}
}.running();
}
}