1.

What do you understand by a static member of a class?

Answer»

We declare a MEMBER as static if it doesn’t depend on any instance of the class, i.e., independent of any OBJECTS. These members are bound to the type and usually accessed USING the type name (rather than the OBJECT references). Static methods and fields are shared between all the objects of a class and can be accessed from any of them, whereas we cannot access the non-static members from a static method. As static methods are not bound to an object, they cannot be overridden. Static fields are initialized through a static block which is executed when a class is loaded by the class loader. Let’s see an example: 

public class Countable {  private static int COUNT; private int x; static {  count = 0; // initialize static member } public Countable(int x) {  this.x = x; Count++; // non-static can access static member } public int getX() { return x; } public static int getCount() {  return count; // only static can access static member } } Countable c1 = new Countable(10);  Countable c2 = new Countable(20); System.out.println("Object count " + Countable.getCount());  // should print 2


Discussion

No Comment Found