简体   繁体   中英

Java class instance outside main method

I am studying Java, and I am a beginner. I tried to create three classes (in the same package). One with main method (JavaApp1), another that I've called "JavaClass1" and the last class "JavaClass2". Here's the JavaClass1's code:

public class JavaClass1 {
public int var1;
public int var2;

}

JavaClass2's code:

public class JavaClass2 {
JavaClass1 ogg = new JavaClass1();
ogg.var1 = 4;
ogg.var2 = 7;

}

In the JavaClass2, Netbeans show me two error, related to the assignments (JavaClass1.var1 and JavaClass.var2) "Package ogg does not exist. expected.

But if i Create the Class instance and attributes assignments inside the main method, there are no problems. Why?

You cannot set the field of an object outside a method.

ogg.var1 = 4;
ogg.var2 = 7;

has to be inside some method.

Classes consist of class fields (like your var1 in the first class) and methods. Methods "do the work", ie execute code. You can initialize fields, but all other code has to be inside a method.

One more note: It is very bad style to have public fields. Please write getters and setters instead.

尝试使用getter和setter,请阅读此http://www.tutorialspoint.com/java/java_encapsulation.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM