Static Methods

static methods

Just like static variables, static methods also belong to the class. However there is no concept of having a separate copy of the method in case of methods though. When you declare a method static, you do not need to instantiate an object to access the static method of the class. You can directly invoke it using the class name. In the above example, method getNumberOfStudents can be declared static. The revised program would be:

class Student {

    static int numberOfStudents;

    private String name;

    public String getFirstName() {
        return this.name;
    }

    public void setFirstName(String name) {
        this.name= name;
    }

    public static int getNumberOfStudents() {
        return numberOfStudents;
    }

    public Student() {
        numberOfStudents++;
    }

    public static void main(String[] args) {
        Student student1 = new Student();
        student1.setFirstName("John");
        System.out.println(Student.getNumberOfStudents());
        Student student2 = new Student();
        student2.setFirstName("Jane");
        System.out.println(Student.getNumberOfStudents());
    }
}

Notice that you do not need the instance reference to invoke getNumberOfStudents method in the System.out.println statements.

Points to remember!

  • You cannot invoke an instance member from a static member. If you think through, it makes perfect sense! A static member exists without an instance, hence referencing an instance member from static member becomes illegal.
  • A static method can invoke another static method
  • If you reference a static member from an instance reference, compiler shows you warning but you can still access it
  • Since static variables are kept in one single memory location, any instance can overwrite the static value set by another instance.

results matching ""

    No results matching ""