See the code snippets below:
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));
}
}
What is the difference between these code snippets? Both output 15
as an answer.
Static method example
Output:
As you can see in the above example that for calling static method, I didn’t even use an object. It can be directly called in a program or by using class name.
Non-static method example
Output:
A non-static method is always be called by using the object of class as shown in the above example.
Key Points:
How to call static methods: direct or using class name:
or
How to call a non-static method: using object of the class: