Having trouble understanding inheritance

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Casey Daniels
    New Member
    • Sep 2010
    • 5

    Having trouble understanding inheritance

    I'm new to Java, and for the life of me I don't understand the whole inheritance concept apparently. I'm trying to create and exit button on a JWindow.

    my main Class reads like this
    Code:
     public static void main(String[] args) {
           JWindow MainWindow = new JWindow();
           MainWindow.setVisible(true);
           MainWindow.setSize(500,500);
           MainWindow.setLocation(100,100);
           ExitButton Fred = new ExitButton();
           MainWindow.add(Fred);
        }
    Add my ExitButton Class Reads
    Code:
    public class ExitButton extends JButton implements ActionListener {
        JButton button = new JButton("Exit");
        
        ExitButton()
        {
            addActionListener(this);
            setSize(10,10);
            setVisible(true);
        }
    
        public void actionPerformed(ActionEvent evt)
        {
            if(evt.getSource()==button)
                {
                System.exit(0);
                }
        }
    
    }
    I'm new to java so at the moment I'm just playing around trying to learn some skills. But the problem I'm having with first off all is when the JWindow Shows up the button also shows up but there is no label. From what I understand when I create "Fred" it should run my Class of ExitButton which tells it to create a button with "Exit" printed on it, all I get is a button that is blank. The other problem is the button isn't doing anything.
    More importantly than just fixing my code, I want to know what is wrong with it.
    Thank You,
    casey
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    Hi Casey!

    When a class, in this case ExitButton extends another class, in this case JButton, an object created from the first is also an object of the second with some changed properties. So, in the ExitButton code, you don't need the line
    Code:
    JButton button = new JButton("Exit");
    but instead you should have the line
    Code:
    super("Exit");
    at the beginning of the constructor. This means "Call the constructor of the parent class with the argument 'Exit'." Now, as the constructor of JButton with the argument "Exit" will create a button with the label "Exit".

    Greetings,
    Nepomuk

    Comment

    • Casey Daniels
      New Member
      • Sep 2010
      • 5

      #3
      That clears up some things for me.


      Thank you for your help.
      Casey

      Comment

      Working...