为什么当我们声明子类的对象时调用超类的构造函数? (Java) [英] Why is constructor of super class invoked when we declare the object of sub class? (Java)

查看:288
本文介绍了为什么当我们声明子类的对象时调用超类的构造函数? (Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑这个代码:

  class Test {
Test(){
System.out。 println(In constructor of Superclass);
}

int添加(int n1,int n2){
return(n1 + n2);
}

void print(int sum){
System.out.println(sums are+ sum);
}
}


class Test1 extends Test {
Test1(int n1,int n2){
System.out.println In constructor of Subclass);
int sum = this.adds(n1,n2);
this.print(sum);
}

public static void main(String [] args){
Test1 a = new Test1(13,12);
Test c = new Test1(15,14);
}
}



如果我们在超类中有一个构造函数,每个对象调用我们
构造子类(例如,对于类Test1的对象'a'调用Test1(int n1,int n2)以及Test())。



为什么会发生这种情况?



这个程序的输出是:



在超类的构造函数中



在子类的构造函数中



$ 25

在超类的构造函数中



在子类的构造函数中



总和是29



解决方案

当调用构造函数时,它可以依赖于其超类中所有被初始化的字段。



请参阅此处


Consider this code:

class Test {
    Test() {
        System.out.println("In constructor of Superclass");
    }

    int adds(int n1, int n2) {
        return(n1+n2);
    }

    void print(int sum) {
        System.out.println("the sums are " + sum);
    }
}


class Test1 extends Test {
    Test1(int n1, int n2) {
        System.out.println("In constructor of Subclass");
        int sum = this.adds(n1,n2);
        this.print(sum);
    }

    public static void main(String[] args) {
        Test1 a=new Test1(13,12);
        Test c=new Test1(15,14);
    }
}

If we have a constructor in super class, it will be invoked by every object tht we construct for the child class(ex. Object 'a' for class Test1 calls Test1(int n1, int n2) as well as Test()).

Why does this happen?

The output of this program is:

In constructor of Superclass

In constructor of Subclass

the sums are 25

In constructor of Superclass

In constructor of Subclass

the sums are 29

解决方案

Because it will ensure that when a constructor is invoked, it can rely on all the fields in its superclass being initialised.

see 3.4.4 in here

这篇关于为什么当我们声明子类的对象时调用超类的构造函数? (Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆