shanwu
shanwu

Reputation: 1685

nested class as testing method in Java

//: innerclasses/TestBed.java
// Putting test code in a nested class.
// {main: TestBed$Tester}

public class TestBed {
  public void f() { System.out.println("f()"); }
  public static class Tester {
    public static void main(String[] args) {
      TestBed t = new TestBed();
      t.f();
    }
  }
} /* Output:
f()
*///:~

I am studying "Think in Java". I am just wondering why the above code doesn't work which should be a way to test each class, and can be removed by deleting TestBed$Tester.class file.

The error msg instructs there should be a public static void main(String[] args) in TestBed class as program entry.

java compile version: javac 1.7.0_40

Upvotes: 0

Views: 318

Answers (1)

Lone nebula
Lone nebula

Reputation: 4878

The main method must be in the public top-level class. That is the one with the same name as the java-file. Here, that's the TestBed-class.

The current main method is in an inner class (namely TestBed$Tester), and can't be used to start a program.

EDIT: I may have been wrong. I took a look in the book you mentioned, and it looks like you're able to run the inner class from the Command Promt by writing:

java TestBed$Tester

Upvotes: 1

Related Questions