简体   繁体   中英

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. 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?

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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