views:

262

answers:

3

Hi,

I am trying to use a class which extends JFrame to build a GUI.

ex : class Deck extends JFrame

The GUI is built in its constructor.

Now when I extend Deck from another class,

ex : class Pile extends Deck

New windows are being created whenever an instance of the subclass (Pile) is started.

Is this happening because the subclass is inheriting the superclass constructor and therefore creating another window?

Can this be avoided without modifying the Deck superclass?

Thanks.

+1  A: 

Is this happening because the subclass is inheriting the superclass constructor and therefore creating another window?

Yes. You extend a JFrame, so you get a JFrame.

super() is always called implicitely before your own constructor, unless you call super(...) or this(...) yourself. This needs to be the first call in your own constructor.

If you really want that behavior, you could write another constructor in your base class (Deck) like that:

public class Deck extends JFrame {
    public Deck(boolean createContent) {
        if( createContent ) {
            getContentPane().add(...);
            // ...
        }
    }

    public Deck() {
        this(true);
    }
}


public class Pile extends Deck {
    public Deck() {
        super(false);
        // ...
    }
}

You will still end up with a JFrame since you extend it, but the child components of your Deck-class are not created.

I'm not sure why you want to do this, so maybe you can add more information to clearify.

Peter Lang
Thanks I will try that. Basically I want to make use of the GUI components that are created in Deck, from other classes. At the moment I am working around it by making these component variables static and accessing them from the other classes by using Deck.JPanel1, for example. But I think there are better ways of doing it...
Kari
+1  A: 

No. The super constructor is always called.

But since you extend JFrame, what's the point of not creating a window? You can hide it using setVisible(false) in Pile's constructor, but that would be strange.

You should redefine your inheritance hierarchy.

Bozho
is it possible to override the superclass's constructor?
Kari
@Kari: No. The super-constructor will be called implicitely before your constructor is called. Please provide more information about why you want to extend a class but not use its behavior.
Peter Lang
+1  A: 

Ya its happening because the subclass is inheriting the super class constructor.In any subclass always first super class constructor is called.

giri