简体   繁体   English

如何在 Java 中用 Generics 扩展抽象 class?

[英]How to extend an abstract class with Generics in Java?

I'm hoping to learn a bit about generics in Java through this question.我希望通过这个问题了解 Java 中的 generics 的一些知识。

I made the following abstract class, which I would like to extend:我做了以下抽象 class,我想扩展它:

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...但是,当我尝试以下列方式扩展 function 时......

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' Class 'ActiveLoansTableCellWithButton' 必须声明为抽象或在 'TableCellWithButton' 中实现抽象方法 'buttonClickHandler(TableCell<DataType, InfoType>)'

Clearly, I'm not overriding my buttonClickHandler method in TableCellWithButton .显然,我没有覆盖TableCellWithButton中的buttonClickHandler方法。 What am I missing that is stopping me from successfully overriding my method?我错过了什么阻止我成功覆盖我的方法?

Screenshot of my IDE:我的 IDE 截图:

在此处输入图像描述

The method buttonClickHandler in TableCellWithButton is package private (has no visiblity modifier). TableCellWithButton中的方法buttonClickHandler是 package 私有的(没有可见性修饰符)。 So the method can only be overriden with classes in the same package.所以该方法只能被同一个 package 中的类覆盖。

In the screenshort provided, both classes are in different packages.在提供的 screenshort 中,两个类都在不同的包中。

So either move both classes to the same package, or adjust the visbility of the method to public (or protected)因此,要么将两个类移动到同一个 package,要么将方法的可见性调整为公共(或受保护)

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

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