Java 如何在超类构造函数中插入子类构造函数中的代码?

Java 如何在超类构造函数中插入子类构造函数中的代码?,java,swing,inheritance,jpanel,Java,Swing,Inheritance,Jpanel,所以我有一个超类,它用一些组件组成一个JPanel。现在我需要这个子类来制作一些单选按钮,并将它们显示在buttonMin之前。现在是我的问题:我如何从我需要的超类中的子类调用代码(请参阅代码以了解应该在哪里调用代码) 我的超类 public class RecordLine extends JPanel{ public RecordLine(Product product){ JTextField fieldName = new JTextField();

所以我有一个超类,它用一些组件组成一个JPanel。现在我需要这个子类来制作一些单选按钮,并将它们显示在buttonMin之前。现在是我的问题:我如何从我需要的超类中的子类调用代码(请参阅代码以了解应该在哪里调用代码)

我的超类

public class RecordLine extends JPanel{

    public RecordLine(Product product){
        JTextField fieldName = new JTextField();
        fieldName.setText(product.getName());
        this.add(fieldName);

        Component horizontalStrut = Box.createHorizontalStrut(20);
        this.add(horizontalStrut);

        //Subclass code should be executed here

        Component horizontalStrut_1 = Box.createHorizontalStrut(20);
        this.add(horizontalStrut_1);

        JButton buttonMin = new JButton("-");
        this.add(buttonMin);
    }
}
我的子类

public class RecordLineDrinks extends RecordLine {

    public RecordLineDrinks(Product product) {
        super(product);

        JRadioButton rdbtnFles = new JRadioButton("Fles");
        this.add(rdbtnFles);
    }

}

你不能直接。。。您可以将超类抽象化,然后实现一个方法,该方法在构造函数中调用了一半

public abstract class RecordLine extends JPanel{
    abstract void midwayUpdate();
然后

public class RecordLineDrinks extends RecordLine {

    public RecordLineDrinks(Product product) {
        super(product);

    }
    void midwayUpdate() {
        JRadioButton rdbtnFles = new JRadioButton("Fles");
        this.add(rdbtnFles);

    }

}
你会有一个“模板方法”

在超类中定义(但不一定在超类中执行任何操作),并从超类的方法调用

在子类中,您可以重写该方法来执行操作

 //Subclass code should be executed here
 this.addExtraButtons();

如果在构造函数中执行此操作,则必须小心一点,因为它将在实例完全初始化之前被调用。将所有这些代码移动到其他
setup()
方法中可能会更干净。

您可能需要更改您的类结构,提供一个可用于创建UI的方法(即
createView
),从中可以通过getter访问其他组件

这样,您可以更改
createView
的工作方式

问题是,您将负责在子类中完全重新创建UI,因此您需要为其他UI组件使用getter方法

另一种选择是,如果您知道要在哪里添加新组件,您可以提供方法的默认实现,这些方法不做任何事情,但允许修改子类

public class RecordLine extends JPanel{

    public RecordLine(Product product){
        JTextField fieldName = new JTextField();
        fieldName.setText(product.getName());
        this.add(fieldName);

        Component horizontalStrut = Box.createHorizontalStrut(20);
        this.add(horizontalStrut);

        //Subclass code should be executed here

        Component horizontalStrut_1 = Box.createHorizontalStrut(20);
        this.add(horizontalStrut_1);

        addBeforeMinButton();

        JButton buttonMin = new JButton("-");
        this.add(buttonMin);
    }

    protected void addBeforeMinButton() {
    }
}

但这通常意味着您事先知道如何修改UI

谢谢,这正是我需要的!非常感谢@普拉杰很高兴这有帮助