Java 基础——初始化

初始化顺序

任何变量的初始化都是在任何方法之前(包括构造方法)。同时父类构造方法先于子类执行,但是回收的时候相反,先回收子类。

参考java编程思想中的

public class People {

    public People() {
        System.out.println("People");
    }
}


public class RTTIDemo {

     People mPeople1 = new People();

    public void print(){
        System.out.println("print");
    }

    People mPeople = new People();

   public RTTIDemo(){
        System.out.println("构造方法");
    }
    
     public static void main(String[] args) {
        RTTIDemo rttiDemo = new RTTIDemo();
    }

}

打印结果:

People
People
构造方法

明白了这一点 ,如果有个student继承了People,代码如下:


public class Animal {

    public Animal() {
        System.out.println("animal");
    }
}

public class Student extends People{
    Animal animal1 = new Animal();

    public Student() {
        System.out.println("student");
    }

    Animal animal = new Animal();

    public static void main(String[] args) {
        new Student();

    }

}

会怎么打印:

People
animal
animal
student

其实,打印结果 对应 任何变量的初始化都是在任何方法之前(包括构造方法)因为两个Animal 对象就是Student类中的一个成员变量,所以这样解释就通了

Static 含义再理解

扫描二维码关注公众号,回复: 5656935 查看本文章

static 可以理解为不是面向对象,面向函数编程的全局方法。因为他可以不依赖对象实例进行调用。

猜你喜欢

转载自blog.csdn.net/sjh_389510506/article/details/88796762