Eragon20
Eragon20

Reputation: 483

Passing variables between classes in Java

I have two separate classes: GameOfLife.java and Grid.java, the latter of which has a paintComponent method. In GameOfLife.java, I have a constantly changing variable, toRepaint, that I need to access in Grid.java.

Here is a section of GameOfLife.java where I set toRepaint:

if (an==0) {
    toRepaint = (String)c.getSelectedItem();
    System.out.println(toRepaint);
}
main.repaint();

Here is where I need to access that variable in Grid.java:

public void paintComponent(Graphics ob) {
    super.paintComponent(ob);
    Graphics2D g1 = (Graphics2D) ob;
    String rep = ??? //This variable should equal the value of toRepaint
}

How can I access this variable?

Upvotes: 1

Views: 2572

Answers (2)

Nate Post
Nate Post

Reputation: 20

To do this, you must make the variable you want to access in another class a public class variable (also known as a field):

public class GameOfLife{
    public static String toRepaint;

    public void yourMethod() {
        //set value, do stuff here
    }
}

And then in Grid.java, you access the class variable using dot syntax:

public void paintComponent(Graphics ob) {
    super.paintComponent(ob);
    Graphics2D g1 = (Graphics2D) ob;
    String rep = GameOfLife.toRepaint;
}

HOWEVER

This is not the best way to do it, but is by far the simplest. In order to follow object-oriented programming we would add the following accessor method to our GameOfLife class:

public static String getToRepaint(){
    return toRepaint;
}

and change our variable declaration to:

private static String toRepaint;

In our Grid class, we instead call the method that accesses the toRepaint variable:

    String rep = GameOfLife.getToRepaint();

This is the heart of object oriented programming, and although it seems redundant, can be quite helpful later on and will help keep code much neater.

Upvotes: -3

My suggestion will be :

  1. Define an interface:

public interface IGame{
    String getName();
}
  1. make the GameOfLife class to implement that interface

and override the method like

@Override
public String getName(){
       return rep;
    }
  1. the Grid.java needs the reference, either pass that in the constructor or use setters getters...

public void paintComponent(Graphics ob) {
    super.paintComponent(ob);
    Graphics2D g1 = (Graphics2D) ob;
    String rep = myInterface.getName();
}

Upvotes: 4

Related Questions