简体   繁体   中英

How do I inherit from a custom LinkedList class?

I need to inherit from IntegerLinkedList, whilst also creating a new variable specific to StringAndIntegerLinkedList . What is it that I am missing?

class IntegerLinkedList {
    int payload;
    IntegerLinkedList next;

    public IntegerLinkedList(int payload, IntegerLinkedList next) {
        this.payload = payload;
        this.next = next;
    }

    class StringAndIntegerLinkedList extends IntegerLinkedList {
        String stringPayload;

    public StringAndIntegerLinkedList(String stringPaylod, int payload, IntegerLinkedList next) {
        this.stringPayload = stringPaylod;
        this.payload = payload;
        this.next = next;
    }

I also have setters and getters for each field in each class.

The error message:

StringAndIntegerLinkedList.java:4: error: constructor IntegerLinkedList in class IntegerLinkedList cannot be applied to given types;
    public StringAndIntegerLinkedList(String stringPaylod, int payload, IntegerLinkedList next) {
                                                                                                ^
  required: int,IntegerLinkedList
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error

Perhaps you're missing the explicit call to the parent class constructor? Try adding that as the first line of the subclass constructor:

super(payload, next);

This is required when the parent class doesn't have a no-arg constructor that the compiler can call automatically. This ensures that the parent class is properly initialized.

Here:

public IntegerLinkedList(int payload, IntegerLinkedList next) {

That is the constructor that the java compiler wants to call from within your derived constructor. Note that it has two parameters.

But the derived constructor has three parameters. So how is the compiler supposed to now which one to use!

One solution: put super(payload, next); as first statement into that derived constructor.

The important part is that any constructor has to either call another constructor in the same class, or a super class constructor. If you leave out that explicit call, the compiler tries to insert one for you. Which it can't do when things to don't add up.

For the theory behind that, see here for example.

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