Sumithra Sumithra - 6 months ago 9
Java Question

I want to know the difference between static method and non-static method

Just see the below codes

code 1

public class A {
static int add(int i,int j) {
return(i+j);
}
}

public class B extends A {
public static void main(String args[]) {
short s=9;
System.out.println(add(s,6));
}
}


code 2

public class A {
int add(int i,int j) {
return(i+j);
}
}

public class B extends A {
public static void main(String args[]) {
A a=new A();
short s=9;
System.out.println(a.add(s,6));
}
}


Now pls explain what is the difference between these codes. Both generate
15
as answer

Answer

A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static.

Example:

class Foo {
    int i;

    public Foo(int i) { 
       this.i = i;
    }

    public static String method1() {
       return "An example string that doesn't depend on i (an instance variable)";
    }

    public int method2() {
       return this.i + 1; // Depends on i
    }
}

You can call static methods like this: Foo.method1(). If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2();

Comments