Reputation: 11
I am not able to compile the following code. Not able to understand the compilation process here. why the main class instances are not been visible to other classes(test1). why it failing at compilation. Please help.
public class test {
public int i = 10;
public static void main(String[] args) {
System.out.println("test main");
}
}
class test1 {
test t = new test();
System.out.println(t.i);
}
Upvotes: 1
Views: 213
Reputation: 62864
The System.out.println(t.i);
statement should be within a block or method.
For example, you can either place it within a block (static or non-static, nevermind).
public class test1 {
test t = new test();
static { //static can be omitted
System.out.println(t.i);
}
}
Or place is within a method
public class test1 {
test t = new test();
public static void printSomething() { //static can be omitted
System.out.println(t.i);
}
}
More info (thanks to @vidudaya):
Upvotes: 7
Reputation: 68915
System.out.println(t.i);
must be inside some method.
public class Test {
public int i = 10;
public static void main(String[] args) {
System.out.println("test main");
}
}
class Test1 {
Test t = new Test();
public void printI(){
System.out.println(t.i);
}
}
Also stick to java naming conventions. Class names must start with capital letters. variables and methods must be in camel case.
Upvotes: 2