ptk
ptk

Reputation: 7653

How to extend an abstract class with Generics in Java?

I'm hoping to learn a bit about generics in Java through this question.

I made the following abstract class, which I would like to extend:

import javafx.scene.control.Button;
import javafx.scene.control.TableCell;

public abstract class TableCellWithButton<DataType, InfoType> extends TableCell<DataType, InfoType> {
    final Button button;

    public TableCellWithButton(Button button) {
        this.button = button;
    }

    @Override
    public void updateItem(
            InfoType item,
            boolean empty
    ) {
        super.updateItem(
                item,
                empty
        );
        if (empty) {
            setGraphic(null);
            setText(null);
        } else {
            button.setOnAction(event -> {
                buttonClickHandler(this);
            });
            setGraphic(button);
            setText(null);
        }
    }

    abstract void buttonClickHandler(TableCell<DataType, InfoType> cell);
}

However, when I try to extend the function in the following manner...

import javafx.scene.control.TableCell;

public class ActiveLoansTableCellWithButton extends TableCellWithButton<Debt, String> {

    @Override
    public void buttonClickHandler(TableCell<Debt, String> cell) {
        // Trying to extend here...
    }
}

I receive the following error:

Class 'ActiveLoansTableCellWithButton' must either be declared abstract or implement abstract method 'buttonClickHandler(TableCell<DataType, InfoType>)' in 'TableCellWithButton'

Clearly, I'm not overriding my buttonClickHandler method in TableCellWithButton. What am I missing that is stopping me from successfully overriding my method?

Screenshot of my IDE:

enter image description here

Upvotes: 1

Views: 225

Answers (1)

k5_
k5_

Reputation: 5568

The method buttonClickHandler in TableCellWithButton is package private (has no visiblity modifier). So the method can only be overriden with classes in the same package.

In the screenshort provided, both classes are in different packages.

So either move both classes to the same package, or adjust the visbility of the method to public (or protected)

Upvotes: 4

Related Questions