Search code examples
javaoopinstance

Access instance of a class in another class


I'm very new to coding and have a strict deadline for this assignment so I couldn't find an explanation I understood very well so I am asking here.

I am makign an instance of my Pokemon class in a another class for my main game. I however need info on how many times a pokemon was defeated in my catch pokemon class as I want a user to only be able to catch a pokemon if they've beat it a certain amount of times. I have no clue how to do this however.

This is how the class is used if it is of any help:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Battle extends JFrame{

public Pokemon fire = new Pokemon("Charmander", "Fire");
public Pokemon water = new Pokemon("Squirtle", "Water");
public Pokemon plant = new Pokemon("Bulbasaur", "Grass");
public Pokemon ground = new Pokemon("X", "Ground");

I have tried something like Battle.pikachu.toString() in the main class to just test how to access it because that is what someone else told me but the battle part confuses me as I don't think it is actually referrign to anything when in my main class.


Solution

  • You should not define your Pokemon inside a Battle. You should instead pass your Pokemon into this Battle class.

    So you should instead define your Pokemon in your Main class:

    public class Main {
      // Your functions...
    
      private ArrayList<Pokemon> getMyPokemons() {
        ArrayList<Pokemon> myPokemonList = new ArrayList<>();
        Pokemon fire = new Pokemon("Charmander", "Fire");
        Pokemon water = new Pokemon("Squirtle", "Water");
        Pokemon plant = new Pokemon("Bulbasaur", "Grass");
        Pokemon ground = new Pokemon("X", "Ground");
        myPokemonList.add(fire);
        myPokemonList.add(water);
        myPokemonList.add(plant);
        myPokemonList.add(ground);
        return myPokemonList;
      }
    
      private void triggerBattle() {
        ArrayList<Pokemon> myPokemonList = getMyPokemons();
        Battle battle = new Battle(myPokemonList);
      }
    }
    

    And in your Battle class,

    public class Battle extends JFrame {
      private ArrayList<Pokemon> myPokemons;
      // Create constructor to receive your Pokemon
      public Battle(ArrayList<Pokemon> myPokemons) {
        this.myPokemons = myPokemons;
      }
    
      // And in other functions within this class, you can access
      // myPokemons list
    }
    

    And of course if you need more information related to the Pokemon, you need to refer to @Boycpu suggestion and add more attributes to your Pokemon class.