首页 > 其他 > 详细

从子类对象在内存中的创建理解构造方法

时间:2020-08-20 12:33:15      阅读:64      评论:0      收藏:0      [点我收藏+]

有子一定要有父,不然会成爷五死

package com.xyf.javaSE;

/**
 * @author xyf
 * @create 2020-08-19-10:25
 */
public class SuperTest {
    public static void main(String[] args) {
        B b=new B(1);
        B b1=new B();
        System.out.println(b.integer);
        System.out.println(b1.integer);

    }
}
class A{
    public A() {
        System.out.println("A的无参构造方法");
    }
    public A(int integer){
        this.integer=integer;
        System.out.println("A的有参构造方法");
    }
    public int integer;
}
class B extends A{
    //int temp;
    public B(){
//这里隐藏了一行代码 super();之前学了,如果构造方法第一行没有调用this()/super(),那么默认也会调用super() System.out.println(
"B的无参构造方法"); } public B(int i) { super(i); System.out.println("B的有参构造方法"); } }

输出

A的有参构造方法
B的有参构造方法
A的无参构造方法
B的无参构造方法
1
0

现在我们来看一下

B b = new B(1);

这行代码在堆中创造B类型的对象b的内存过程

技术分享图片

 

本图省略了非构造方法的压栈和运行过程

 

从子类对象在内存中的创建理解构造方法

原文:https://www.cnblogs.com/happyxyf/p/13534094.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!