Thread: Explain static
View Single Post
Old 08-15-2008, 06:38 AM   PM User | #5
shyam
Senior Coder

 
shyam's Avatar
 
Join Date: Jul 2005
Posts: 1,563
Thanks: 2
Thanked 163 Times in 160 Posts
shyam will become famous soon enough
Quote:
Originally Posted by twodayslate View Post
Code:
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
Code:
class Student {
  private static studentNum=0;
  private myNumber;
  public Student() {
    this.myNumber = studentNum++;
  }
  public static int getStudentNum() { 
    return studentNum; 
  }
  public int getNumber() {
    return myNumber;
  }
}
Code:
Student bob   = new Student(),
        dylan = new Student();

Student.getStudentNum(); // returns 2
bob.getNumber(); // gives 0
dylan.getNumber(); // gives 1
__________________
You never have to change anything you got up in the middle of the night to write. -- Saul Bellow
shyam is offline   Reply With Quote
Users who have thanked shyam for this post:
twodayslate (08-15-2008)