简体   繁体   English

超类子类构造函数java

[英]Super class Sub class Constructor java

I am new to Java. 我是Java新手。 In the below code I am having some difficulty to understand the concepts. 在下面的代码中,我很难理解这些概念。

class A {

    private Integer intr;

    public A(Integer intr) {
        this.inrt = intr;
    }

    public Integer getIntr() {
        return intr;
    }
}

class B extends A {

    public B(Integer intr) { //Eclipse asking me to create this constructor. 
        super(intr);
    }
}

I am getting confused why I need to create that kind of constructor as eclipse suggesting. 我很困惑为什么我需要创建这种构造函数作为eclipse建议。 What is in there? 那里有什么?

A sub-class's constructor calls the constructor of its super-class ( A in your case). 子类的构造函数调用其超类的构造函数(在您的情况下为A )。 If your sub-class B has no constructor, the compiler automatically creates a constructor without any parameters. 如果您的子类B没有构造函数,编译器会自动创建一个没有任何参数的构造函数。 That constructor automatically calls the constructor with no parameters of the base class A . 该构造函数自动调用构造函数,不带基类A参数。

Since your base class A has a constructor with a parameter, the compiler does not generate a constructor without parameters for it, and therefore you must explicitly create a matching constructor with a single parameter in your sub class B. 由于基类A具有带参数的构造函数,因此编译器不生成没有参数的构造函数,因此必须在子类B中显式创建具有单个参数的匹配构造函数。

The are other alternatives to creating that constructor in B : 在B中创建该构造函数的其他替代方法是:

You can define a no parameters constructor in A : 您可以在A中定义一个无参数构造函数:

public A()
{
   this.inrt = 0;
}

This will allow the no parameters constructor automatically generated for B to call the matching constructor in A . 这将允许为B自动生成的无参数构造函数来调用A的匹配构造函数。

Or you can explicitly define a no parameters constructor in B that calls the existing constructor of A : 或者您可以在B中显式定义一个无参数构造函数来调用A的现有构造函数:

public B()
{
    super(0);
}

If there is no constructor, there is default constructor, which also calls super's default constructor. 如果没有构造函数,则有默认构造函数,它也调用super的默认构造函数。 But when you created constructor in parent, there is no default constructor in parent. 但是当您在父级中创建构造函数时,父级中没有默认构造函数。

The only way to instantiate a A is to use the A(Integer) constructor. 实例化A的唯一方法是使用A(Integer)构造函数。 Unless the super class implements a nullary constructor, every subclass has to explicitely call a super constructor at the beginning of its self constructor. 除非超类实现了一个nullary构造函数,否则每个子类都必须在其自构造函数的开头明确地调用一个超级构造函数。

But the subclass contructor does not necessarily need the exact same signature. 但是子类构造函数不一定需要完全相同的签名。 For example, those are also valid: 例如,那些也是有效的:

public B() {
    super(42);
    // other B specific stuff
}

public B(Integer i, String s) {
    super(i);
    // other B specific stuff
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM