Skip to content
October 27, 2008 / Narayan

Static method

public class Student {

private static int totalStudents;

// Other details omitted.

// Constructor.

public Student() {

// Details omitted.

// Automatically increment the student count every time we

// instantiate a new Student.

totalStudents++;

}

// The following three methods are now static methods; .

public static int getTotalStudents() {

return totalStudents;

}

public static void setTotalStudents(int x) {

totalStudents = x;

}

public static void reportTotalEnrollment() {

System.out.println(“Total Enrollment: ” + getTotalStudents());

}

public static void main (String[] args) {

//Static methods can be invoked from a class filename

//or invoke it from the object related class

Student.setTotalStudents(4);

Student.reportTotalEnrollment();

//optional

/*

*Student s1 = new Student();

*s1.setTotalStudent();

*s1.reportTotalEnrollment();

*/

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: