How does the get() method work?

Asked

Viewed 47 times

-2

I wanted to understand the method get(), how it works and what is it serving in this code (preferably wanted an explanation of imaginary form without technical names).

package exemplo_oo;

public class Game {

    private Player player;
    private Inimigo inimigo;
    
    public Game() {
        player = new Player();
        inimigo = new Inimigo();
    }
    
    public Player getPlayer() {
        return player;
    }
    
    public Inimigo getInimigo() {
        return inimigo;
    }
    
    public static void main(String[] args) {
        Game game = new Game();
        Player player = game.getPlayer();
        player.atacarInimigo(game.getInimigo());
        System.out.println(game.getInimigo().life);
    }
    
}

package exemplo_oo;

public class Player {
    private int life = 100;
    
    public void atacarInimigo(Inimigo inimigo) {
        inimigo.life--;
    }
}

    package exemplo_oo;

public class Inimigo {
    public int life = 5;
}

2 answers

2


A method get() usually aims to obtain a value, an object or even a class.

Then take a look at polymorphism and encapsulation.

Trying to make it clear, from your example:

The method getPlayer() returns an object of the type Player, therefore its variable player can be assigned to this get method. That is, it takes an object of type Player who belongs to the class Game and assigns in its variable player.

To try to make it a little clearer:

Using the example to method getInimigo():

As stated, the method will return an object of the type Inimigo, and that means you can have access to methods and variables public of that class Inimigos, so he can access the variable life defined in the class Inimigos.

That is, when calling a method get(), usually you will get something return, of the type defined.

1

Complementing Higor’s answer: get methods (as well as set methods) is also a convention. Nothing prevents you from returning Imigo instead of getInimigo. But like any convention, it’s there to help you. Ides implement code generation facilitators for you and there is even a library (https://projectlombok.org/) which provides annotations generating getters and setters at compile time.

In the case of Javabeans components it is not just a convention but one of the 3 items to be implemented (the other two are having a constructor without arguments and implementing java.io.Serializable).

Browser other questions tagged

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