-2

I have single class in java having two methods. one is public static void main(String args []). when i call other method inside main i get above error.

class Test {
    public static void main(String[] args) {
        method();
    }

    private void method() {
        System.out.println("hello");
    }

}
Joel
  • 4,732
  • 9
  • 39
  • 54
  • see also http://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static –  Feb 13 '14 at 18:25
  • This question was [answered](http://stackoverflow.com/questions/4969171/cannot-make-static-reference-to-non-static-method?rq=1) multiple times. – Warlord Feb 13 '14 at 18:26

3 Answers3

2

When this is unclear, you should follow some basic java tutorials first. This is a nice start: What is the best java tutorial site.

Community
  • 1
  • 1
R. Oosterholt
  • 7,720
  • 2
  • 53
  • 77
1

Solution - make the other method static as well - OR make an instance to it through the class Test (using the new operator)

ALTERNATIVE 1 (using static)

 class Test {
  public static void main(String[] args) {
    method();
 }

 private static void method() {
    System.out.println("hello");
 }

}

ALTERNATIVE 2 (using an instance of the class Test)

class Test {
  public static void main(String[] args) {
    Test test = new Test();
    test.method();
 }

 private void method() {
    System.out.println("hello");
}

}
Björn Hallström
  • 3,775
  • 9
  • 39
  • 50
0

Creating an instance of Test, because non static methods should be called from instance:

new Test().method();
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28