Accessing static members

18 January 2012 By Nithya Vasudevan 239 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×
  • 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()

Tags: