具有类名作为返回类型的java实例变量

1 java static instance-variables return-type

对于下面的代码,我创建了一个实例变量,其类名作为返回类型

class classtype{
    static classtype x;

    public static void main(String...a){
         System.out.println(x);
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码输出到null指示这个具有类名作为返回类型的实例变量保持字符串类型值,显然但是当我尝试初始化它时

static classtype x="1";
Run Code Online (Sandbox Code Playgroud)

它给出了类型不匹配错误 java.Lang.String

如果有人能解释,请

Sur*_*tta 6

ERROR1:

x="1";
Run Code Online (Sandbox Code Playgroud)

你不能这样做

因为Classtype 不是一种String类型.

误差2:

印花 null

class Classtype{
         static Classtype x = new Classtype();
         public static void main(String...a){
         System.out.println(x);
         }
       }
Run Code Online (Sandbox Code Playgroud)

确保 System.out.println(x); 默认情况下打印Objects toString 方法.

由于你x还没有初始化它现在是null.

所以按照print(printlninvokes print)方法

打印一个字符串.如果参数为null,则打印字符串"null".否则,根据平台的默认字符编码将字符串的字符转换为字节,并且这些字节的写入方式与write(int)方法完全相同.

要打印需要课堂上String ovveridetoString方法Classtype.并遵循java命名约定.类名以大写字母开头.

随着你所有的代码变得

public class Classtype {


        static Classtype x = new Classtype();
        public static void main(String...a){
        System.out.println(x);

      }

        @Override
        public String toString() {
        // TODO Auto-generated method stub
        return "This is ClassType toString";
        }

}
Run Code Online (Sandbox Code Playgroud)