andrea1493
andrea1493

Reputation: 55

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?

Upvotes: 1

Views: 1740

Answers (2)

mohit sharma
mohit sharma

Reputation: 1070

Try using getter and setters, read this http://www.tutorialspoint.com/java/java_encapsulation.htm

Upvotes: 0

J Fabian Meier
J Fabian Meier

Reputation: 35795

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", i.e. 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.

Upvotes: 4

Related Questions