[英]java instance variable with class name as return type
For the code below I have created an instance variable with class name as return type 对于下面的代码,我创建了一个实例变量,其类名称为返回类型
class classtype{
static classtype x;
public static void main(String...a){
System.out.println(x);
}
}
Above code outputs to null
indicating that this instance variable having class name as return type holds string type values and obviously but when i try to initialize it 上面的代码输出为
null
表明此具有类名作为返回类型的实例变量保存字符串类型值,但是很显然,当我尝试初始化它时
static classtype x="1";
it gives type mismatch error found in java.Lang.String
它给出在
java.Lang.String
发现的类型不匹配错误
please if anyone can explain 请任何人都可以解释
Error1: 错误1:
x="1";
You cannot do that 你不能这样做
Because Classtype
is not a String
type. 因为
Classtype
不是String
类型。
Error2: 错误2:
Printing null
打印
null
class Classtype{
static Classtype x = new Classtype();
public static void main(String...a){
System.out.println(x);
}
}
Make sure that System.out.println(x);
确保
System.out.println(x);
here by default prints the Objects toString
method. 默认情况下,这里打印Objects
toString
方法。
Since your x
haven't initialize it is null now. 由于您的
x
尚未初始化,因此现在为null。
So as per print ( println
invokes print
) method 因此,按照每个print (
println
调用print
)方法
Prints a string.
打印一个字符串。 If the argument is null then the string "null" is printed.
如果参数为null,则输出字符串“ null”。 Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
否则,将根据平台的默认字符编码将字符串的字符转换为字节,并以完全write(int)方法的方式写入这些字节。
To print require String
ovveride
the toString
method in Classtype
class. 要打印需要
String
ovveride
的toString
的方法Classtype
类。 And follow the java naming conventiones. 并遵循Java命名约定。 Class names starts with caps.
类名以大写字母开头。
With all your code becomes 随着所有的代码成为
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";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.