JavaSE阶段2_内部类

package 内部类;

public class Test{
    public static void main(String[] args){
           // 初始化Bean1,成员内部类

        Test test = new Test();    
        Test.Bean1 bean1 = test.new Bean1(); 
           bean1.I++;
           // 初始化Bean2,静态内部类
           Test.Bean2 bean2 = new Test.Bean2();

           bean2.J++;
           //初始化Bean3
          Bean.Bean3 bean3 = new Bean().new Bean3();
          bean3.k++;
    }
    class Bean1{
           public int I = 0;
    }

    static class Bean2{
           public int J = 0;
    }
}

class Bean{
    class Bean3{
           public int k = 0;
    }
}

###//创建静态内部类对象的一般形式为:  外部类类名.内部类类名 xxx = new 外部类类名.内部类类名()

###//创建成员内部类对象的一般形式为:  外部类类名.内部类类名 xxx = 外部类对象名.new 内部类类名()

public class Test {
    public static void main(String[] args)  {
        Outter outter = new Outter();
        outter.new Inner().print();
    }
}


class Outter
{
    private int a = 1;
    class Inner {
        private int a = 2;
        public void print() {
            int a = 3;
            System.out.println("局部变量:" + a);
            System.out.println("内部类变量:" + this.a);
            System.out.println("外部类变量:" + Outter.this.a);
        }
    }
}
//321


//1)成员内部类的引用方式必须为 Outter.Inner.
//
//2)构造器中必须有指向外部类对象的引用,并通过这个引用调用super()
class WithInner {
    class Inner{

    }
}
class InheritInner extends WithInner.Inner {

    // InheritInner() 是不能通过编译的,一定要加上形参
    InheritInner(WithInner wi) {
        wi.super(); //必须有这句调用
    }

    public static void main(String[] args) {
        WithInner wi = new WithInner();
        InheritInner obj = new InheritInner(wi);
    }
}

###//匿名类
//只要一个类是抽象的或是一个接口,那么其子类中的方法都可以使用匿名内部类来实现
//匿名内部类也就是没有名字的内部类
//
//正因为没有名字,所以匿名内部类只能使用一次,它通常用来简化代码编写
//
//但使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口


###//在接口上使用匿名内部类
interface Person {
    public void eat();
}

public class Demo {
    public static void main(String[] args) {
        Person p = new Person() {
            public void eat() {
                System.out.println("eat something");
            }
        };
        p.eat();
    }
}

###//匿名内部类的基本实现
abstract class Person {
    public abstract void eat();
}

public class Demo {
    public static void main(String[] args) {
        Person p = new Person() {
            public void eat() {
                System.out.println("eat something");
            }
        };
        p.eat();
    }
}
###//Thread类的匿名内部类实现
public class Demo {
    public static void main(String[] args) {
        Thread t = new Thread() {
            public void run() {
                for (int i = 1; i <= 5; i++) {
                    System.out.print(i + " ");
                }
            }
        };
        t.start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值