CJR
CJR

Reputation: 3592

How to pass class object to another class that is using super();

I have been working all day, so this may be a no brainer but my tired brain fails to see it. If that is the case, sorry for the stupid question. Now, to my problem.

I want my Gui class to have access to the class Validator. In the main class, which creates all classes, the Gui and Validate class is created.

Like this:

public class Main{

    public static void main(String[] args){
        Gui gui = new Gui();
        Validate validate = new Validate();
    }   

}

Now, I want my Gui class to have access to Validate class and be able to access its methods.

Here is my Gui class constructor:

public class Gui extends JFrame implements ActionListener{

//A list of variables here...

public Gui(){

    super("BANK");

    //rest of the constructor.

Now, how do I let my Gui class access the validate while using the super(); ?

Upvotes: 0

Views: 134

Answers (3)

Fevly Pallar
Fevly Pallar

Reputation: 3109

If you mean super() on this line super("BANK"); , then you can't , this super("BANK") refers to JFrame's constructor as your Gui class is extending JFrame. It only accept parameter for String title and/or GraphicConfiguration gc.

You need modify your constructor :

 private Validate validate;
 public Gui(Validate validate){
    super("BANK"); // this super refers to JFrame constructor
    this.validate = validate;

}

Upvotes: 0

Mognom
Mognom

Reputation: 214

You have no control from that class over what super does, so you either pass it to the constructor as an argument and save it on a variable or make validate static so everyone can access it (tho is not recomendable and you would only be able to have one instance of it).

public class Main{

    public static void main(String[] args){
        Validate validate = new Validate();
        Gui gui = new Gui(validate);
    }   

}

public class Gui extends JFrame implements ActionListener{

//A list of variables here...
private Validate validate;

public Gui(Validate val){

    super("BANK");
    validate = val;

    //rest of the constructor.
}

This way Gui has a reference to validate and can access any public methods and variables.

Upvotes: 0

M Abbas
M Abbas

Reputation: 6479

You would try something like:

public class Gui extends JFrame implements ActionListener{
    private Validate validate;
    public Gui(Validate validate){
        super();
        this.validate = validate;
        //rest of the constructor.
    }
    ...
}

    public class Main{

        public static void main(String[] args) {
            Validate validate = new Validate();
            Gui gui = new Gui(validate);
        }
    }

Upvotes: 3

Related Questions