在JAVA中,我们可以使用预定义的类名作为变量名吗?

时间:2014-10-20 19:33:17

标签: java class

一位采访者问了这个问题。我回答错了。我是对的吗?

3 个答案:

答案 0 :(得分:2)

是的,我们可以使用预定义的类名作为变量。以下代码将完美地运作

public class Test
{
    public static void main(String[] args) 
    {
        int BufferedOutputStream = 3; //BufferedOutputStream is predefined class
        System.out.println(BufferedOutputStream);
    }
}

也可以使用用户定义的类名作为变量名。示例

public class Test
{
    public static void main(String[] args) 
    {
        Test2 Test2 = new Test2();
        System.out.println(Test2.a);
    }
}

public class Test2
{
    public int a = 2;
}

答案 1 :(得分:0)

我建议预定义的类名可以用作变量名,但是小写。

喜欢" Box box = new Box()"。只有" Box"只能用作类名。 "盒"可以用作对象名称。

"盒"否则被保护为类名。

答案 2 :(得分:0)

  

在Java中,我们可以使用预定义的类名作为变量名吗?

在Java中命名的基本规则是,您不能使用关键字作为类的名称,变量的名称,也不能使用用于包的文件夹的名称。这在Java Specification Language中说明:

  

<强> 3.9。关键字

     

由ASCII字母组成的50个字符序列保留用作关键字,不能用作标识符§3.8

     

关键字:

abstract   continue   for          new         switch
assert     default    if           package     synchronized
boolean    do         goto         private     this
break      double     implements   protected   throw
byte       else       import       public      throws
case       enum       instanceof   return      transient
catch      extends    int          short       try
char       final      interface    static      void
class      finally    long         strictfp    volatile
const      float      native       super       while

这些是Java世界中的无效名称:

int boolean = 5; //invalid!
boolean goto = false; //invalid!
String default = "string"; //invalid!
com.foo.assert.MyClass myClass = new com.foo.assert.MyClass(); //invalid! Because of assert used as folder

但是,使用Java中的任何预定义类都不会导致此类编译器错误,因为Java预定义类不是关键字:

String Integer = "foo";
System.out.println(Integer);

输出:

foo
相关问题