Answer the question
In order to leave comments, you need to log in
Can a static method call a non-static one?
The book The Complete Java Reference by Herbert Schildt says: "Methods declared static are subject to a number of restrictions.
- They can only call other static methods.
...
but:
public class Main {
public String nonStaticF1() {
return "inside non static method";
}
public static void main(String[] args) {
Main m1 = new Main();
System.out.println(m1.nonStaticF1());
}
}
//output:
//inside non static method
Answer the question
In order to leave comments, you need to log in
You have created an instance of the Main class and called the instance method through an object reference. In a static method, instance methods can be called if the instance itself is created in it.
public static void main(String[] args) {
//создание экземпляра и помещение ссылки на экземпляр в переменную m1
Main m1 = new Main();
//теперь через m1 есть доступ к методу nonStaticF1()
System.out.println(m1.nonStaticF1());
}
Non-static methods are instance methods of a class.
Static methods are methods of the class itself.
A static method, without having an instance of the class at its disposal, cannot call a non-static method of anyone.
Having an instance of the class ( m1
in the example), you can use its non-static methods from anywhere.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question