从其他 class 访问 java 中最终字段的正确方法

Correct way for accessing final fields in java from other class

从其他 class 访问最终字段的好方法是什么?为什么。

A) 通过将其设为私有并在 getter 和 setter 方法

中提供功能,将其与其他 class 隔离
public class Game extends JPanel {
 private final Racquet racquet;

 public Game() {
    racquet = new Racquet(this);
 }
}

public class Ball {
 private Game game;

 Ball(final Game game) {
    this.game = game;
 }

 void move(int speed) {
    if (collision()) {
        y = game.getRacquet().getTopY() - DIAMETER;
    } 
 }
}

public class Racquet {
 final Game game;

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

 public int getTopY() {
    return Y;
 }
}

B) 保持默认,直接使用variable.methodname。

public class Game extends JPanel {
 final Racquet racquet;
}

public class Ball {

 void move(int speed) {
  if (collision()) {
   y = game.racquet.getTopY() - DIAMETER;
  } 
 }
}

public class Racquet {
 final Game game;

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

 public int getTopY() {
 return Y;
 }
}

直接访问 final 字段会提高性能吗?

与其使用 getter 移动球拍,不如使用一种方法在内部为您完成。

void move(int speed) {
  if (collision()) {
    racket.move(diameter)
   } 
}
//inside racket
public int move(int diameter){
    return this.Y - diameter;
}

或者,如果需要,将移动拆分为 moveUpmoveDown 等。以及 return 通过直径后的计算值。这将取决于许多因素,例如球的位置。您可以检查球的位置并决定调用哪个方法和移动球拍。

最好现实地考虑一下。

你可以有一个 Player class:

  • 负责判断球的位置。
  • 移动球拍

实际上,您的 Racket 不会知道 Ball 在哪里,或者 Ball 不会知道您使用 Racket击中它,Player 知道它。

如果你想遵循 OOP 指南,那么不要直接访问变量(即 public),而是让方法为你完成工作,并给你结果,它是 Tell, Don't Ask。如果需要,保留 getter 以供显示。