0

I am trying a simple example in java:

class student{  
    int id;  
    String name;  

    void stud(int id,String name){  
    id = id ;
    name = name;  
    }  
    void display(){System.out.println(id+" "+name);}  

    public static void main(String args[]){  
    student s1 = new student(); 
    s1.stud(1,"sss");  
    s1.display();  
    }  
}  

it gives me an o/p as 0 and null

and the following program :

class student{  
    int id;  
    String name;  

    void stud(int i,String n){  
    id = i ;
    name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  

    public static void main(String args[]){  
    student s1 = new student(); 
    s1.stud(1,"sss");  
    s1.display();  
    }  
}  

gives me an output as 1 sss

Why does changing the formal parameters to names different from member variables of the class works correctly?

2

2 Answers 2

5

Because when you declare a parameter in

void stud(int id,String name)

you are hiding (shadowing) the instance variable id. Therefore, whenever id is accessed within the method stud, it will refer to the local id, not the instance variable.

If you want to access to the instance variable, use the this keyword:

void stud(int id,String name) {
    this.id = id; 
    // ...
}

this.id will refer to the instance variable, while id will refer to the parameter (local).

Sign up to request clarification or add additional context in comments.

Comments

1

You need to reference it using this.id = id; That's because once you pass a parameter with the same name it's a local variable, using this makes it clear you're talking about the classes variable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.