我正在经历toString()
概念,我在System.out.println("hi");
之前写了public static void main(String args[])
public class ToString {
private String city;
private int pincode;
public ToString(String city,int pincode){
this.city=city;
this.pincode=pincode;
}
System.out.println("hi");
@Override
public String toString(){
return city+" "+pincode;
}
public static void main(String args[]){
ToString s = new ToString("pppp",11038);
System.out.println(s);
}
在运行代码时,它给了我以下错误
java.lang.ClassFormatError: Method "<error>" in class Basics/ToString has illegal signature "(Ljava/lang/Object;)Ljava/lang/System$out$println;"
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:476)
Exception in thread "main" Java Result: 1
是什么原因?为什么我们不能在System.out.println()
之前写public static void main(String args[])
?
答案 0 :(得分:0)
你得到这个的原因是因为任何可执行代码都必须包含在方法中。要解决您的错误,您必须将System.out.println()
放在方法中,但您可能已经知道了。
除非将其放在初始化程序块中,否则不能在方法之外执行代码。这看起来像这样:
public class ToString {
private String city;
private int pincode;
{
System.out.println("hi");
}
public ToString(String city, int pincode) {
this.city = city;
this.pincode = pincode;
}
//etc
}