Java——内部类

public class Circle {
    private double radius = 0;
    public static int count = 1;

    public Circle(double radius) {
        this.radius = radius;
    }

    public Draw getInstance(){
        return new Draw();
    }

    class Draw {     //成员内部类
        private int count=2;
        public void drawSahpe() {
            System.out.println(radius);  //外部类的private成员
            System.out.println(Circle.this.count);   //外部类的静态成员
        }
    }

    //局部内部类
    public void getWoman(){
        class Woman extends People{
            private String name="woman";
            public void print(){
                System.out.println("局部内部类: "+name);
            }
        }
        Woman woman=new Woman();
        woman.print();
    }

    //静态内部类
    public static class man{
        public void print(){
            System.out.println("静态内部类");
        }
    }

    //匿名内部类
    public void get(){
        //匿名内部类是没有名字的类
        //多态,本身就继承了Thread或者实现了一个Runnable接口,通过重写方法实现某种执行逻辑
         new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println("thread: "+Thread.currentThread().getName()+" 第"+i+"次");
                    try {
                        Thread.currentThread().sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }.start();

         Runnable run=new Runnable(){
             @Override
             public void run() {
                 for (int i = 0; i < 5; i++) {
                     System.out.println("runnable: "+Thread.currentThread().getName()+" 第"+i+"次");
                 }
             }
         };
         new Thread(run).start();
    }
}


public class People {
    public People(){}
}

public class TestDemo {
    public static void main(String[] args) {
        Circle circle=new Circle(4);
        //成员内部类的两种调用方式
//        Circle.Draw draw = circle.new Draw();
        Circle.Draw draw = circle.getInstance();
        draw.drawSahpe();

        //局部内部类的调用
        circle.getWoman();

        //静态内部类的调用
        Circle.man man = new Circle.man();
        man.print();

        //匿名内部类的调用
        circle.get();
    }
}

静态内部类和成员内部类的区别:

匿名内部类是否能够继承其他的类或者实现其他的接口:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值