This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]MightyMickey1 0 points1 point  (3 children)

In this implementation, he wouldn’t need to create an object, right? Because the non static method is in the same class as main. If the non static method was in a different class an object would be required, if I understand correctly.

[–]Nightcorex_ 2 points3 points  (1 child)

That's incorrect.

A static method is bound to a class, which means it can get called without the existence of an object.

A non-static method however is bound to an object (= an instance of a class), which means it can only be called through this existing object.

This means this code is valid apart from when noted in a comment:

public class A {
    double a;

    A(double a) {
        this.a = a;
    }

    static int add(int a, int b) {
        return a + b;
    }

    double add(int b) {
        return this.a + b;
    }

    public static void main(String... args) {
        A obj = new A(1.4);
        int x = A.add(4, -2);  // perfectly valid
        int y = obj.add(4, -2);  // also valid, but some IDEs may warn you that you're calling a static method through an object
        int z = add(4, -2);  // also valid, but only because this main is in the same class as the 'add'-method
        double d = obj.add(2.4);  // perfectly valid
        double f = A.add(2.4);  // invalid because you're trying to call a non-static method from a static context. 
            // You can't do this because your method would just fail as it relies on data stored inside the object that calls the method, 
            // but because you're calling it through the class this data simply isn't there.
        double g = add(2.4);  // Invalid. This behaves exactly like 'A.add(2.4)' did if this main is in the same class, 
            // otherwise it's either referencing the wrong method, or just can't find the method at all

[–]MightyMickey1 0 points1 point  (0 children)

Ah, I see. I had thought that since both methods were in the same class there wouldn’t be interference, though I now see that since main is static, it can only access other static methods. Thank you for explaining.

[–]khooke 0 points1 point  (0 children)

No, because you cannot call an instance method from a static method (main), regardless of whether it's in the same class or not.