Java Nested Class Question

0 Developer John · February 9, 2015
Why isn't this valid when making a Java nested class:


public class Hello{

public static void main(String[] args){

class Test{
System.out.println();
}
}
}

-Thanks!8-)

Post a Reply

Replies

- page 2
Oldest  Newest  Rating
0 Developer John · February 9, 2015
Okay, so a class body can only contain fields that are variable declarations, but why?
0 Duba Blaz · February 9, 2015
I think that it's not possible to add any statement inside nested class without methods. You can add variables, but to use for example System.out.println("Hello"); outside method will not work.
0 Developer John · February 9, 2015
Oh wow, I can't believe I forgot to create a method. What kind of statements are acceptable inside the class body, but outside a constructor or method body? 
0 Duba Blaz · February 9, 2015
public class Hello{

public static void main(String[] args) {
        class Test  {
            private void method() {
                System.out.println("Hello");

            }
        }
        
        Test test = new Test();
        
        test.method();

}
}

Hi,

I think that you must put some methods there, so you can call it outside nested class as in example above. If there is no methods, "AnnotationName" compile error will appear.
  • 1
  • 2

Java / Android Development

107,228 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator