Java基础笔记36——内部类

内部类:定义在一个类中的类,即嵌套类

 

注意:

1.内部类可以访问外部类所有的属性与方法,不需要创建对象

2.外部类访问内部类的属性或方法时,必须创建对象

(1)在类中访问:

内部类类名 对象名 = new 内部类类名();

(2)在类以外访问:

内部类类名 对象名 = 嵌套内部类的类的对象.new 内部类类名();

3.如果内部类与外部类的属性或方法重名,内部类的优先级>外部类的优先级

4.不能定义static变量


外部类修饰符:public <default>
外部类修饰符:public <default> protected private

 

例子:

package com.lqh.chapter05;

//外部类
public class Outer {
    // 外部类变量
    String out = "outer";
    String repeat = "22";

    // 内部类
    class Inner {
        String in = "inner";
        String repeat = "88";
        //static int num = 0;不能定义static变量

        // 内部方法
        public void inMethod() {
            System.out.println("内部类方法");
        }
        
        public void visitOutMethod() {
            System.out.println("访问外部类的变量:" + out);
            outMethod();
        }
        
        public String getRepeat() {
            //repeat是内部类的值,而Outer.this.repeat则是外部类的值
            return repeat + " "+ Outer.this.repeat;
        }
    }

    public void outMethod() {
        System.out.println("外部类方法");
    }
    
    public void visitInMethod() {
        //在类中访问内部类
        Inner inner = new Inner();
        inner.visitOutMethod();
    }
    public static void main(String[] args) {
        Outer outer = new Outer();
        outer.visitInMethod();
        //在类以外中访问内部类
        Inner inner = new Outer().new Inner();
        inner.inMethod();
        System.out.println(inner.getRepeat());
    }
}

输出结果为:

访问外部类的变量:outer
外部类方法
内部类方法
88 22

posted @ 2021-09-17 19:43  `青红造了个白`  阅读(35)  评论(0)    收藏  举报