K
K
Kolos902015-11-09 19:16:11
Java
Kolos90, 2015-11-09 19:16:11

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

I see a non-static method called from a static one. What do I not understand?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly Vitrenko, 2015-11-09
@Kolos90

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());
    }

PS Empty brackets when calling a method without arguments are required. //nonStaticF1().

N
nirvimel, 2015-11-09
@nirvimel

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 ( m1in the example), you can use its non-static methods from anywhere.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question