PDA

View Full Version : Explain static


twodayslate
08-13-2008, 10:54 PM
private static studentNum=0;
public Student() {
studentNum++;
}
public static int getStudentNum() { return studentNum; }

public int getStudentNum is only static so it can return the static StudentNum correct? To call it you would say Student.bob.getStudentNum();

Am I understanding this?

shyam
08-14-2008, 07:44 PM
public int getStudentNum is only static so it can return the static StudentNum correct? To call it you would say Student.bob.getStudentNum();?

who is bob?

you access static methods only via the class name so, Student.getStudentNum() (assuming that the snippet you posted is part of the Student class)

twodayslate
08-15-2008, 03:19 AM
Thanks for the reply!who is bob?

you access static methods only via the class name so, Student.getStudentNum() (assuming that the snippet you posted is part of the Student class)
Student bob = new Student();
So to get bob's student number what do you call? It can't be Student.getStudentNum();, is it Student.bob.getStudentNum();?

icm9768
08-15-2008, 04:57 AM
It would be Student.getStudentNum(). Static variables are shared among ALL instances of the class so it doesn't require you to reference it via any particular instance (bob in your case), nor should you for clarity sake. Using Student.bob.getStudentNum() would work, but it will create a warning when you compile your code.

Just as a side note, in case you didn't already realize, that each Student class you instantiate will not have a unqiue studentNum. Every instance will have the same id (i.e. The total number of Student objects you have created).

shyam
08-15-2008, 07:38 AM
Student bob = new Student();
So to get bob's student number what do you call? It can't be Student.getStudentNum();, is it Student.bob.getStudentNum();?

as icm9768 has rightly pointed out there is no bob's student number...if you want to store bob's student number you should store it in a member variable sorta like this
class Student {
private static studentNum=0;
private myNumber;
public Student() {
this.myNumber = studentNum++;
}
public static int getStudentNum() {
return studentNum;
}
public int getNumber() {
return myNumber;
}
}


Student bob = new Student(),
dylan = new Student();

Student.getStudentNum(); // returns 2
bob.getNumber(); // gives 0
dylan.getNumber(); // gives 1

twodayslate
08-15-2008, 11:13 PM
Thanks.
This was a question for my summer assignment. (Dont worry, you did not do my homework for me)
I understand it now. Thanks!