Java getter vs this [英] Java getter vs this

查看:127
本文介绍了Java getter vs this的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常通用的场景,我使用setter函数设置变量并仅在本地使用变量。

This is a very generic scenario, where I am setting a variable using setter function and using the variable only locally.

class Main {
 private String str;

 public Main(String value)
  setStr(value);
 }

 private String getStr() {
    return str;
 }

 private void setStr(String str) {
    this.str = str;
 }

 public void display() {
    //METHOD1
    System.out.println(getStr());
    //METHOD2
    System.out.println(this.str);
  }
}




  1. 什么在显示函数中两个METHOD1 / 2之间遵循更好的做法,基本上是使用str变量的更好方法。

  1. What would be the better practise to follow between the two METHOD1/2 in display function, basically what would be the better way of using "str" variable.

私有getter / setter函数甚至有意义吗?

Does it even make sense to have private getter/setter functions?


  • Ivard


推荐答案

如果getter是私有的,并且只是返回一个私有变量,那么它不是需要,恕我直言(即我更喜欢访问它的第二种方法)。

If the getter is private, and doesn nothing more than returning a private variable, it isn't needed, IMHO (i.e. I prefer the second method of accessing it).

但是如果getter是公共的而不是final的,因此可以由子类重新定义,那么你必须决定是否要获取getter返回的潜在重写值,或者你是否想要显示方法中私有字段的值。

But if the getter was public and not final, and could thus be redefined by a subclass, then you'd have to decide if you want to get the potentially overridden value returned by the getter, or if you want the value of the private field in the display method.

这篇关于Java getter vs this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆