Hirad Gorgoroth
Hirad Gorgoroth

Reputation: 389

Can I change a variable of an object

I have a student object that can hold name and mark.

public class Student{
    Public String name;
    Public int mark;
    public Student (int argMark, String argName)
    { mark=argMark; name=argName;}
}

when I create a student as :

  Student john = new Student(70, "John");

I need to change the mark later while keeping the previous marks

  Student temp = john; 
  temp.mark = 60; 

when I print them out they both have 60 marks

 System.out.println(temp.mark);
 System.out.println(john.mark);

the system shows the answer of : 60 for both of them

I know I can extend a class and have a method for get, set methods and override it, but this is not acceptable for my assignment. Is there any other way to do this?

Upvotes: 0

Views: 194

Answers (2)

Akash Thakare
Akash Thakare

Reputation: 22972

You can create copy constructor and by doing that you can have new reference with the same attribute values in your temp. Currently John and Temp have same reference and change in one will get reflected in other.

public Student (Student student) { 
   this.mark = student.getMark(); 
   this.name = student.getName();
}

Few suggestions,

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201409

When you say

Student Temp = John;  // <-- typo for John

you assign a reference to the same instance that Jhon references. Based on your question, you expect a second instance. Something like

Student Temp = new Student(John.Mark, John.Name); 

Also, by convention Java variable names start with a lower case letter.

Upvotes: 1

Related Questions