内部类

Wrting a class within another is allowed in Java. The class written within is called nested class, and the class that holds the inner class is called the outer class.

1. Nested  Classes


class Outer_Demo {

    class Inner_Demo {

    }

}

Nested classes are divided into two types 

  • Non-static nested classes: The are the non-static members of a class.
  • Static nested classes: These are the static members of a class.

2. Inner Classes(Non-static Nested Classes)

Inner  classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then inner class can be made private.And this is also used to access the private members of a class.

Inner classes are of three types depending on how and where you define them. 

  • Inner class 
  • Method-local Inner Class 
  • Anonymous Inner Class 

 

- Accessing the Private Members: 内部类可以访问外部类的私有成员

// 实例化一个内部类(必须要有其对应的外部类实例存在)

Outer_Demo outer = new Outer_Demo();

Outer_Demo.Inner_Demo inner = outer.new Inner_Demo()

- Method-local Inner Class: 

在方法里定义的内部类是一个局部类型,只能在函数内使用。即一个method-local inner class只能在函数内部实例化。

 

- Anonymous Inner Class:

对于匿名内部类,其声明和初始化是同时进行的。其作用通常是为了重写某个方法

// 创建一个匿名内部类并初始化

AnonymousInner an_inner = new AnonymousInner() {  // 创建一个匿名内部类,其实是创建了目标类的子类对象

    @override

    public void my_method() {  // 重写基类方法

        

    }

}

2. static nested class

静态内部类就像外部类的一个静态成员,可以无需实例化外部类就访问该静态内部类。就想静态成员一样,静态内部类不能访问外部类实例成员变量和方法。

class MyOuter {
    static class Nested_Demo {
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fanqiliang630

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值