static vs non-static Java

static vs non-static Java

Java novices are not much aware of static vs non-static or static to non-static calling. Let us find the rules through a program.

In the following code, show() method is non-static and display() is static. The question is "Can we call a non-static method from static method?". Everyone says simply "no" because it requires an object to call. Anyhow, let us observe the compiler message.


static vs non-static
Output screen of static vs non-static Java

This is an usual compiler message every Java professional come acrosses.

Now let us see the combinations.

show() display() Result
non-static non-static works
static non-static works
static static works
non-static static does not work

The above table can easily be remembered. Only one combination does not work – calling non-static member from static member (it requires object).

Anyhow do small programs yourself and check the rules of combinations to have command over coding.

Can a class be static?

No. A class cannot be static. But static classes are possible with inner classes. Read Static Nested Classes.

Pass your comments and suggestions on this tutorial "static vs non-static Java".

3 thoughts on “static vs non-static Java

Leave a Reply

Your email address will not be published. Required fields are marked *