Java 为什么要在变量名前加_(下划线)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20677249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:32:19  来源:igfitidea点击:

Why we add _ (underscore) before variable name?

javavariables

提问by

I know this can be silly question but I actually don't know that why we add _ (underscore) before variable name in java while Variable declaration.

我知道这可能是一个愚蠢的问题,但我实际上不知道为什么我们在变量声明时在 java 中的变量名之前添加 _ (下划线)。

I have tried on google but I actually can't find exact answer of it. So anyone tell me is it just a type of declaration as user want or is there any proper mechanism and reason to do so.

我试过谷歌,但实际上我找不到确切的答案。所以有人告诉我这只是用户想要的一种声明,还是有任何适当的机制和理由这样做。

Thank You In Advance.

先感谢您。

回答by Liping Huang

this should be an idiomatic usage.

这应该是惯用的用法。

回答by Maroun

Sometimes it is used in order to distinguish class membersfrom local variables:

有时它用于区分类成员和局部变量:

public class MyClass {
   private int _salary;

   public MyClass(int salary) {
       _salary = salary
   }
} 

However, you should follow Java Naming Conventionsthat doesn't recommend using that. You can simply name the class member without the leading _and do:

但是,您应该遵循不推荐使用它的Java 命名约定。您可以简单地命名没有前导的类成员_并执行以下操作:

this.salary = salary;

回答by Dennis Traub

An underscore in front usually indicates a instance variable as opposed to a local variable. It's merely a coding style that can be omitted in favor of "speaking" variable names and small classes that don't do too many things.

前面的下划线通常表示实例变量而不是局部变量。它只是一种可以省略的编码风格,有利于“说出”变量名和不做太多事情的小类。

回答by Francesco Irrera

The use of " _ " (underscore) must be evaluated carefully.
Use " _ " to indicate class attributes is used a lot in C + +. In Java, it is not necessary because the language has the keyword this.

必须仔细评估“_”(下划线)的使用。
用“_”表示类属性在C++中使用较多。在 Java 中,没有必要,因为该语言具有关键字this