java java实例变量和方法同名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9960560/
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
java instance variable and method having same name
提问by rubixibuc
In java can an instance variable and a method have the same name without any instability or conflict?
在java中,实例变量和方法可以同名而没有任何不稳定或冲突吗?
I want to make sure if I can get away with compiling it, that it wont cause any error down the road.
我想确保我是否可以编译它,它不会导致任何错误。
回答by Coffee
Yes it's fine, mainly because, syntactically , they're used differently.
是的,这很好,主要是因为,在语法上,它们的使用方式不同。
回答by JREN
It's completely fine because methods and variables are called differently.
这完全没问题,因为方法和变量的调用方式不同。
Code:
代码:
String name = "myVariable";
public String name() {
return "myMethod";
}
System.out.println(name()); // Brackets for method call
System.out.println(name); // No brackets for variable call
Output:
输出:
myMethod
myVariable
我的方法
我的变量
回答by Code Enthusiastic
The only conflict I could think of is
我能想到的唯一冲突是
int sameName = 5;
public int sameName() {
//method body
return 100;
}
If you write "this.sameName"when you are supposed to write "this.sameName()"and vice-versaat some place in the program then annihilation of the code has just begun.
如果你在应该写“this.sameName() ”的时候写“this.sameName”,反之亦然,那么代码的毁灭才刚刚开始。
回答by Pcgomes
I actually have ran into an issue, which is very specific. It just manifests itself in Java 8 (using Nashorn), but not in Java 6 (using Rhino). If it try to access an instance variable of a Java object via Javascript, the []
operator returns the method instance instead.
我实际上遇到了一个非常具体的问题。它只在 Java 8(使用 Nashorn)中表现出来,而不在 Java 6(使用 Rhino)中表现出来。如果它尝试通过 Javascript 访问 Java 对象的实例变量,则[]
操作符将返回方法实例。
Let's suppose I'm running the following Java declaration:
假设我正在运行以下 Java 声明:
class MyClass {
private boolean isSet=false;
public boolean isSet() { return isSet; }
}
If I manipulate an object of such class in Javascript, and then try to access it with []
operator, I get the method reference.
如果我在 Javascript 中操作此类的对象,然后尝试使用[]
运算符访问它,我将获得方法引用。
var obj = new MyClass();
var myfields = (myclass.getClass()).getDeclaredFields();
var myfieldname = myfields[0].name;
// The following prints the method declaration, not the boolean value:
// [jdk.internal.dynalink.beans.SimpleDynamicMethod boolean MyClass.isSet()]
println( obj[myfieldname] );
UPDATE: Apparently Nashorn's method overloading resolution mechanism("implicitly" or non-intentionally) gives higher precedence to methods without arguments over instance fields with the same name.
更新:显然Nashorn 的方法重载解析机制(“隐式”或非故意)为没有参数的方法提供了更高的优先级,而不是同名的实例字段。
回答by MK.
You can, but it is an anti pattern, should be avoided, and can be caught by analytics like so:
你可以,但它是一种反模式,应该避免,并且可以像这样被分析捕获: