内部类
* 内部类的访问规则:
* 1,内部类可以直接访问外部类中的成员,包括私有。
* 之所以可以直接访问外部类中的成员,是因为内部类中特有了一个外部类的引用,格式:外部类名。this
* 2,外部类要访问内部类,必须建立内部类对象。
*
* 访问格式:
* 1,当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中。
* 可以直接建立内部类对象。
* 格式
* 外部类名.内部类名 变量名=外部类对象.内部类对象;
* Outer.Inner in=new Outer().new Inner();
*
* 2,当内部类在成员位置上,就可以被成员修饰符所修饰。
* 比如,private:将内部类在外部类中进行封装。
* static:内部类就具备了static特性。
* 当内部类被static修饰后,只能直接访问外部类中的静态成员。出现了访问局限。
*
* 在外部其他类中,如何直接访问静态内部类的静态成员?
* new Outer.Inner().function();
*
* 在外部其他类中,如何直接访问静态内部类的非静态成员?
* Outer.Inner.function();
*
* 注意:当定义内部类中定义了静态成员,该内部类必须是static的。
* 当外部类中的静态方法访问内部类时,内部类也必须是static的。
*
*
* 当描述事物时,事物的内部还有事物,该事物用内部类来描述。
* 因为内部事务在使用外部事物的内容。
*
* 当一个类要访问另一个类内部的成员时,就把他定义到那个类里面,之后封装起来private
class Outer
{
// private int x=3;
private static int x=3;
static class Inner//内部类 可以私有private class Inner
{
int x=4;
static void function()
{
int x=6;
System.out.println("inner:"+x);
// System.out.println("inner:"+Outer.this.x);3
// System.out.println("inner:"+this.x);//4
}
}
static class Inner2
{
void show()
{
System.out.println("inner2");
}
}
public static void method()
{
new Inner2().show();
// Inner.function();
}
// void method()//Inner
// {
// Inner in=new Inner();
// in.function();
// }
}
public class InnerClassDemo {
public static void main(String[] args) {
//在外部其他类中,访问静态内部类的静态成员
Outer.Inner.function();
// 在外部其他类中,访问静态内部类Inner中的非静态成员function
// new Outer.Inner().function();
// Outer outer=new Outer();
// outer.method();
//直接访问内部类中的成员。
// Outer.Inner in=new Outer().new Inner();
// in.function();
}
}
* 内部类只有被定义到成员位置时才能被私有/静态
*
* 定义在方法中的类不能用静态,类中的成员,方法都不能是静态
*
* 1,不可以被成员修饰符修饰
* 2,可以直接访问外部类中的成员,因为还持有外部类中的引用。
* 但是不可以访问它所在的局部中的变量。只能访问被final修饰的局部变量。
class Outer3
{
int x=3;//可以被内部类访问
void method(final int a)
{
class Inner//不能用private,因为private只能修饰成员变量,现在Inner属于局部变量
{
final int y=4;
void function()//
{
System.out.println(Outer3.this.x);
System.out.println(y);
}
}
// new Inner().function();
}
}
public class InnerClassDemo3 {
public static void main(String[] args) {
//在这里只调用method方法Inner不会运行(没对象非静态不会运行)
new Outer3().method(7);
}
}
* 匿名内部类:
* 1,匿名内部类其实就是内部类的简写格式
* 2,定义匿名内部类的前提
* 内部类必须是继承一个类或者实现接口。
* 3,匿名内部类的格式:new父类或者接口(){定义子类的内容}
* 4,其实匿名内部类就是一个匿名子类对象。而且这个对象有点胖。可以理解为带内容的对象。
* 5,匿名内部类中定义的方法最好不要超过3个。
abstract class AbsDemo
{
abstract void show();
void method(){}
}
class Outer4
{
int x=3;
/*class Inner extends AbsDemo
{
void show()
{
System.out.println("method"+x);
}
// void method()
// {
// System.out.println("method"+x);
// }
}*/
public void function()
{
new AbsDemo() {//AbsDemo的匿名子类对象
// AbsDemo() d=new AbsDemo(){
int x=5;
void show() {
// TODO Auto-generated method stub
System.out.println(x);
}
void abc()
{
System.out.println();
}
}.show();//.abc()也可以
// new Inner().show();
// new Inner().method();
// d.show();
// d.abc();//编译失败,父类没有abc方法
}
}
public class InnerClassDemo4 {
public static void main(String[] args) {
Outer4 outer4=new Outer4();
outer4.function();
}
}