0

Why is there a compilation error with the line if (i == 0) { print(); }? Is it because main is static, even though it is within the class of A?

public class A {
        private void print() { System.out.print(foo() + " "); }
        public String foo() { return "AAA"; }
        public static void main(String[] args) {
              A[] arr = { new A(), new B() };
              for (int i = 0; i < 2; i++) {
/***/                  if (i == 0) { print(); }
}
}
}
public class B extends A {
       private void print() { System.out.println("%" + foo() + " "); }
       public String foo() { return "BBB"; }
       public void bar() { print(); }
}
student
  • 25
  • 6
  • main is static; print is not. Very basic stuff; which honestly, you shouldn't ask for; but learn from tutorials, books, etc. – GhostCat Jun 28 '16 at 11:49
  • Learn what `static` means: [Understanding Class Members](https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html) – Jesper Jun 28 '16 at 11:52

2 Answers2

2

There is a compiler error because you are trying to call the non-static method print from the static method main. And yes, main must be static.

You need to create an instance of A, and then call the print method on that instance:

A a = new A();
a.print();
explv
  • 2,709
  • 10
  • 17
1

print() is non-static. This means that it is meant for objects of the class A. You cannot call it from main() because it is static, and static methods belong to the class. To call print(), you can do:

A a = new A();
a.print();
dryairship
  • 6,022
  • 4
  • 28
  • 54