子类不继承父类字段

时间:2016-11-17 01:01:41

标签: java inheritance subclass

我有一个子类但问题是由于某种原因,它不会继承主类的字段。我尝试过公开而不是私有(即使你原本应该能够从子类访问私有字段),但即使这样也行不通。

package com.testfoler;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Fenetre extends JFrame {

    private Panneau pan = new Panneau();
    public JButton bouton = new JButton("Go");
    public JButton bouton2 = new JButton("Stop");
    private JPanel container = new JPanel();
    private JLabel label = new JLabel("Le JLabel");

    public Fenetre() {
        this.setTitle("Animation");
        this.setSize(300, 300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);

        container.setBackground(Color.white);
        container.setLayout(new BorderLayout());
        container.add(pan, BorderLayout.CENTER);
        bouton.addActionListener(new BoutonListener());
        bouton.setEnabled(false);
        bouton2.addActionListener(new Bouton2Listener());

        JPanel south = new JPanel();
        south.add(bouton);
        south.add(bouton2);
        container.add(south, BorderLayout.SOUTH);
        Font police = new Font("Tahoma", Font.BOLD, 16);
        label.setFont(police);
        label.setForeground(Color.blue);
        label.setHorizontalAlignment(JLabel.CENTER);
        container.add(label, BorderLayout.NORTH);
        this.setContentPane(container);
        this.setVisible(true);
    }
}

// Those are the subclasses
class BoutonListener implements ActionListener {
    public void actionPerformed(ActionEvent arg0) {
        bouton.setEnabled(false);
        bouton2.setEnabled(true);
    }
}

class Bouton2Listener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        bouton.setEnabled(true);
        bouton2.setEnabled(false);
    }
}

2 个答案:

答案 0 :(得分:1)

您将字段标记为私有,因此无法继承它们。

此外,这些"子类"不要扩展您的Fenetre课程。请注意。

应该是:

class BoutonListener extends Fenetre implements ActionListener 

而不是:

class BoutonListener implements ActionListener 

两种情况。

答案 1 :(得分:1)

//Those are the subclasses 
class BoutonListener implements ActionListener{
    public void actionPerformed(ActionEvent arg0) {
       bouton.setEnabled(false);
       bouton2.setEnabled(true);
   }
}

您的“子类”不会扩展任何超类。它们不是Fenetre的子类。