简体   繁体   English

关于super在子类构造函数中?

[英]About super in subclass constructor?

I'm trying to use and understand the constructor correct in a subclass. 我试图在子类中使用和理解构造函数是正确的。 Let's begin with some bits of code: 让我们从一些代码开始:

// creating an object
 account = new CreditAccount(accountNumber, personalNumber);

// constructor in superclass Account
public Account(int aNumber, int pNumber) {
accountNumber = aNumber;
personalNumber = pNumber;
}

// constructor in the subclass CreditAccount
public CreditAccount(int aNumber, int pNumber) {
super(accountNumber, personalNumber);
}

When I create the new object, creditAccount , I send accountNumber and personalNumber to the constructor in the subclass. 当我创建新对象creditAccount ,我将accountNumberpersonalNumber发送到子类中的构造函数。 But am I doing right? 但我做得对吗? (It's not working!) Am I going to use super in the subclass to get hold of the content of the constructor of the superclass? (它没有用!)我是否会在子类中使用super来获取超类构造函数的内容?

Since subclasses only inherits datamembers and method from the superclass and not the constructor, I'm curious how to do this right? 由于子类只从超类而不是构造函数继承数据库和方法,我很好奇如何做到这一点?

You didn't specify what isn't working, so I assume it is the simple invokation error: 你没有指定什么不起作用,所以我认为它是简单的invokation错误:

public CreditAccount(int aNumber, int pNumber) {
   super(accountNumber, personalNumber);
}

you should invoke the super() with the relevant parametrs, which are the input of the derived class` constructor: 你应该使用相关的参数调用super() ,这些参数是派生类`构造函数的输入:

public CreditAccount(int aNumber, int pNumber) {
   super(aNumber, pNumber);
}

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

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