关于java:程序运行顺序及原理分析

代码

package text.Base.ExecutionSequence;

class Demo0 {

    int a;
    String b;

   public Demo0(){
       System.out.println("Demo0:Argumentless constructor");
   }
   public Demo0(String b) {
       this.b = b;
       System.out.println("Demo0:There are parameter constructors");
   }
   public Demo0(String b, int a){
       this.b = b;
       this.a = a;
       System.out.println("Demo0:There are parameter constructors");
   }
    {
        System.out.println("Demo0:Non-static code blocks");
    }
    static{
        System.out.println("Demo0:Static code blocks");
    }
    public void sout(){
        System.out.println("Demo0:Common method");
    }
}

class Demo1 extends Demo0 {

    int c;
    String d;
    public Demo1(){
        System.out.println("Demo1:Argumentless constructor");
    }
    public Demo1(int c) {
        this.c = c;
        System.out.println("Demo1:There are parameter constructors");
    }
    public Demo1(int c, String d) {
        this.c = c;
        this.d = d;
        System.out.println("Demo1:There are parameter constructors");
    }
    {
        System.out.println("Demo1:Non-static code blocks");
    }
    static{
        System.out.println("Demo1:Static code blocks");
    }
    public void sout(){
        System.out.println("Demo1:Common metchod");
    }

    public static void main(String[] args) {
        System.out.println("==============Demo0==========");
//        Demo0 demo0 = new Demo0();
        System.out.println("==============Demo1==========");
        Demo1 demo1 = new Demo1();
    }
}


运行后果

1.父类动态代码块
2.子类动态代码块
3.父类非动态代码块
4.父类构造函数
5.子类非动态代码块
6.子类构造函数

剖析

1.办法区:

mina()办法是一个程序的入口,程序从mian()办法进入,mian()办法被static关键字润饰,存在于办法区,因而程序首先执行的是存在于办法区中的办法、变量等,而其有父类首先执行父类的,再执行子类

2.堆:

程序执行完办法区内的办法、变量等,就会执行非动态代码块,而非动态代码块属于对象,对象存在于堆中,因而在实例化对象的时候首先执行非动态代码块,再执行构造函数。

3.栈

实例化对象的时候实例的进去的对象的援用存在于栈中,通过援用指向堆中的对象,通过援用的形式调用对象的一般办法。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理