Good day to all)) Explain that there is magic?)

public class Game { private static final String GAME_NAME = "XO"; private Player[] players; public String getGameName() { return GAME_NAME; } 

and there is a class

 public class ConsoleView { private final Game game; public ConsoleView(final Game game) { this.game = game; } public void showGameName() { System.out.println(game.getGameName()); } } 

So, I do not understand what this field announcement is?

 private final Game game; 

And I cannot call methods through Game , but only through game .

  • Looks like a bad Game class design. Logically, the GAME_NAME field should not be static, since each object of this class can have its own name. Otherwise, the name access method should also be made static, independent of the specific object. - Vlad from Moscow

1 answer 1

The keyword final relative to the class fields means the immutability of this field. That is, after the call:

 public ConsoleView(final Game game) { this.game = game; } 

You can no longer replace the game object with another object (but you can change its state ).

And I cannot call methods through Game, but only through game

Since the getGameName() method of the Game class is not static, it can only be called through an instance of this class. To call this method through Game you need to declare it as static :

 public static String getGameName() { return GAME_NAME; } 
  • it is necessary to distinguish the declaration of a field as final, and a parameter in a method. In the method, this is just a hint to the compiler. - a.chugunov
  • @post_zeew how to understand this post here - "Game game" ??? - Dasha Novikova
  • @DashaNovikova, This is the declaration of the Game object of the game class. - post_zeew
  • @post_zeew why not so Game game = new Game (); What's the Difference? - Dasha Novikova
  • one
    @DashaNovikova There is practically no difference. If the variables are not given any value ("int a; Object o; Game game"), then the constructor of your class will do it for you - the reference types will be null, and the primitives will accept 0, false, etc. But in this case, you set the variable game value, which is passed in the parameter of the designer himself - SlandShow