Java|剖析类内的五类成员:属性、方法、构造器、代码块、内部类( 二 )

4.1.1 可以有输出语句 。
4.1.2 可以对类的属性、类的声明进行初始化操作 。
4.1.3 不可以对非静态的属性初始化 。即不可以调用非静态的属性和方法 。
4.1.4 若有多个静态的代码块,那么按照从上到下的顺序依次执行 。
4.1.5 静态代码块的执行要先于非静态代码块 。
4.1.6 静态代码块随着类的加载而加载,且只执行一次 。
4.2 非静态代码块:没有static修饰的代码块 。
1 可以有输出语句 。
2 可以对类的属性、类的声明进行初始化操作 。
3 除了调用非静态的结构外,还可以调用静态的变量或方法 。
4 若有多个非静态的代码块,那么按照从上到下的顺序依次执行 。
5 每次创建对象的时候,都会执行一次 。且先于构造器执行 。
程序中成员变量赋值的执行顺序:
① 声明成员变量的默认初始化;
② 显式初始化、多个初始化块依次被执行(同级别下按先后顺序执行);
③ 构造器再对成员进行初始化操作;
④ 通过”对象.属性”或”对象.方法”的方式 。
5 类的成员之内部类当一个事物的内部,还有一部分需要完整结构进行描述,而这部分的完整结构又只为外部事物提供服务,那么整个内部的完整结构最好使用内部类。
An inner class is a class that is defined inside another class. Why would you want to do that? There are three reasons:
① Inner class methods can access the data from the scope in which they are defined—including the data that would otherwise be private.
② Inner classes can be hidden from other classes in the same package.
③ Anonymous inner classes are handy when you want to define callbacks without writing a lot of code.
在Java 中,允许一个类的定义位于另一个类的内部 。前者称为内部类(Inner class) ,后者称为外部类(out class) 。
Inner class 一般用在定义它的类或语句块之内,外部引用它时必须给出完整的名称 。
Inner class的名字不能与包含它的外部类类名相同 。
内部类可以区分为:
① 成员内部类(static成员内部类和非static成员内部类);
② 局部内部类(不用修饰符);
③ 匿名内部类 。
成员内部类作为类的成员的角色:
和外部类不同 ,Inner class还可以声明为private 或protected;
可以调用外部类的结构;
Inner class可以声明为 static 的,但此时就不能再使用外层类的非 static的成员变量 。
成员内部类作为类的角色:
可以在内部定义属性 、方法 、构造器等结构;
可以声明为abstract类 ,因此可以被其它的内部类继承;
可以声明为 final;
编译以后生成 OuterClass$InnerClass.class字节码文件 (也适用于局部内类) 。
public class Main {public static void main(String[] args) {Outer outer = new Outer();outer.test();}}// Demonstrate an inner class.class Outer {int outer_x = 100;void test() {Inner inner = new Inner();inner.display();}// this is an inner classclass Inner {void display() {System.out.println("display: outer_x = " + outer_x);}}}The nesting is a relationship between classes, not objects. A LinkedList object does not have subobjects of type Iterator or Link.
There are two benefits about inner class: name control and access control.
However, the Java inner classes have an additional feature that makes them richer and more useful than nested classes in C++. An object that comes from an inner class has an implicit reference to the outer class object that instantiated it. Through this pointer, it gains access to the total state of the outer object.
匿名内部类不能定义任何静态成员、方法和类,只能创建匿名内部类的一个实例 。一个匿名内部类一定是在new的后面,用其隐含实现一个接口或实现一个类 。
在Java 类中 ,可用 static 修饰属性 、方法 、代码块 、内部类 。

【Java|剖析类内的五类成员:属性、方法、构造器、代码块、内部类】


推荐阅读