[英]Java - underscore
不知道它是否重复(找不到像“java character allowed”这样的搜索词)。 我在测试面试中遇到了这个问题:
class _ {_ f; _(){}_(_ f){_ t = f; f = t;}_(_ f, _ g){}}
所以我的答案是否定的,但我错了。 有人可以解释我这是如何编译的? (我尝试使用我的IDE,我很惊讶它是编译好的)
就标识符而言,下划线字符被视为Java中的字母。 JLS第3.8节涵盖了标识符可以包含的内容:
标识符是无限长度的Java字母和Java数字序列,第一个必须是Java字母。
和
“Java字母”包括大写和小写ASCII拉丁字母AZ(\\ u0041- \\ u005a)和az(\\ u0061- \\ u007a),并且由于历史原因,ASCII下划线(_,或\\ u005f)和美元符号($,或\\ u0024)。 $字符只能用于机械生成的源代码,或者很少用于访问遗留系统上预先存在的名称。
所以这个编译。 它定义了一个名为_
的类,其中一个成员变量具有相同的类名_
称为f
。 有3个构造函数 - 一个没有参数,什么都不做,一个有一个类型_
f
参数,一个有两个参数f
和g
,类型_
什么都不做。
第二个构造函数声明一个类型为_
的局部变量t
并将参数f
赋给它,然后将t
赋值给f
(它不触及实例变量f
)。
Java中的标识符可以包含任何Unicode字符,除非标识符既不是关键字,也不是bool或null文字。 他们不应该以数字开头。 有关详细信息,请查看参考:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8
您的示例代码满足这些条件。 稍微重命名后的代码如下:
class SomeClass
{
SomeClass f;
SomeClass() {}
SomeClass(SomeClass f)
{
SomeClass t = f;
f = t;
}
SomeClass(SomeClass f, SomeClass g) {}
}
你看它以class _
开头,所以我们声明一个名为(下划线字符)的类。 如果用一个可能用来命名类的单词替换_
,这可能会变得更加明智。
class thing { //we're declaring a class called 'thing'
thing f; //the class contains a member variable called 'f' that is of type thing
thing(){ //this is the constructor
}
//It was a default constructor, it doesn't do anything else
//Here is another constructor
thing(thing f) { //This constructor takes a parameter named 'f' of type thing
// We are declaring a local variable 't' of type thing, and assigning the value of f that was passed in when the constructor was called
thing t = f;
f = t; //Now we assign the value of t to f, kind of an odd thing to do but it is valid.
}
//Now we have another constructor
thing(thing f, thing g){ //This one takes two parameters of type thing called 'f' and 'g'
} //And it doesn't do anything with them...
} //end class declaration
总而言之,它编译是因为它是有效的java代码,因为我试图在上面解释。
太棒了!
class _ //Underscore is a valid name for a class
{
_ f; //A reference to another instance of the _ class named f
_() //The constructor of the _ class
{
//It's empty!
}
_(_ f) //A second constructor that takes an other instance of _ called f as a parameter
{
_ t = f; // A new reference to a _ object called t that now points to f
f = t; // f points to t (which, well, points to f :) )
}
_(_ f, _ g) //A third constructor with two parameters this time of _ instances.
{
//It's empty!
}
} // End of class definition!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.