pass objects from one class to another

Asked

Viewed 24 times

-2

I have the following objects in the Game class as I call these objects in the class Main?

team1=new Team(t1, t2, t3);
team2=new Team(e1, e2, e3);
  • To all moderators, I know it sounds like a simple question, we should have an answer for her already inside the O.R. But I couldn’t find one to demonstrate as a duplicate, so I took the liberty of replying.

1 answer

1


There are several ways.

One of them is to use a constructor in your class Main:

public class Game {

    public static void main(String[] args) {
        Main main = new Main(new Team(), new Team());
    }
}

public class Main {

    Team teamUm;
    Team teamDois;

    public Main(Team teamUm, Team teamDois) {
        this.teamUm = teamUm;
        this.teamDois = teamDois;
    }
}

Another way is by set methods, invoked within the Game:

public class Game {

    public static void main(String[] args) {
        Main main = new Main();
        main.setTeamUm(new Team());
        main.setTeamDois(new Team());
    }
}

public class Main {

    Team teamUm;
    Team teamDois;

    public void setTeamUm(Team teamUm) {
        this.teamUm = teamUm;
    }

    public void setTeamDois(Team teamDois) {
        this.teamDois = teamDois;
    }
}

I hope it helps!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.