Java--内部类

本文详细介绍了Java内部类的概念、分类及使用方法,包括成员内部类、静态内部类、匿名内部类等,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

内部类
1、内部类中的类只能通过外部类调用,内部类可以访问外部类的私有属性。
2、内部类分为成员内部类(静态内部类,非静态内部类),匿名内部类(用于只调用极少次数的类,省去声明类的过程,直接在内部写,如监听器),局部内部类(用的极少,即定义在方法内部),基本语法在下方代码中体现(不含局部内部类)。

package cn.ldedu;

/**
 * 测试内部类
 * @author Lenovo
 *
 */

abstract class people{  //此处用于下方匿名内部类调用,不一定非要用抽象类,普通类也可以
    abstract void eat();
}

public class testInClass{
    int shape=0;
    static int age=10;

    class In{
        int shape=1;
        public void show(){

            System.out.println("shape="+shape);//访问自己的shape
            System.out.println("shape2="+testInClass.this.shape);//访问外部类的shape
            System.out.println(age);
        }
    }

    static class temp{
        static int shape=3;
        public void show(){
            System.out.println(age); //只能访问外部类的静态变量或方法
            System.out.println("shape="+shape);//访问自己的静态shape
        }



    }

    public static void main(String[] args) {
        testInClass ti=new testInClass();
        In i=ti.new In();   //非静态内部类初始化规则
        temp t=new testInClass.temp();//静态内部类初始化规则

        i.show();
        t.show();


        people tt=new people(){             //匿名内部类
            public void eat(){
                System.out.println("eat hahah");
            }
        };

        tt.eat();
    }



}

运行截图如下:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值