Accessing static members

  • To access instance variable/ method we use dot operator on the reference variable of the class. For example, to access the name instance variable of Student class, we create a reference variable and use it to access it.
  • Student s1 = new Student("John");
    System.out.println(s1.name);
    
  • Similarly for accessing the static member (variable/method) we use the dot operator on the class name, since static member belongs to a class and to any particular instance.

General Syntax:

className.staticVariable
className.staticMethod

package com.ibytecode.keywords.staticdemo;
class Student
{
	private String name;
	int id;
	static int count; //Initialized to zero
	
	public Student(String name) {
		this.name = name;
		id = ++count;
	}
	
	public static int getCount()
	{
		return count;
	}
}

public class StudentDemo {
	public static void main(String[] args) {
		Student s1 = new Student("John");
		Student s2 = new Student("Kumar");
		Student s3 = new Student("Ram");
		
		System.out.println(s1.name);
		System.out.println(s2.name);
		System.out.println(s3.name);
		
		System.out.println("Number of Students created: " 
						+ Student.count);
		System.out.println("Number of Students created: "
						 + Student.getCount());
	}	
}

In the above example, to access the static members we used dot operator on the class name.

Student.count
Student.getCount()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.