Static Members: Static Methods and Static Variables

Why do we need Static members?

There are situations in which the method’s behaviour does not depend on the state of an object. So, there will be no use of having an object when the method itself will not be instance specific.

Let us consider another situation where in we want to keep a count of all the instances instantiated from a particular class. Suppose we declare an instance variable to do the job, it won’t work. Its because the instance variables are initialised back to their default value each time a instance is created. So we need some varaible which will be independent of the instances created.

The answer to both the situations is to use the “static” modifiers, in other words static members.

Read more

Overriding v/s Hiding

Many people have heard that you can’t override a static method. This is true – you can’t. However it is possible to write code like this: class Foo { public static void method() { System.out.println(“in Foo”); } } class Bar extends Foo { public static void method() { System.out.println(“in Bar”); } } This compiles and … Read more

%d bloggers like this: