0

I have a project that involves creating objects of varying types that inherit methods and variables from a super class, but when I try to change the variable in the subclass (to a value inputted through the constructor) the variable remains the same value it is initialized to in the super class.

This is one of the variables the super makes:

public int grade = 0;

and this is what happens in the subclass (newGrade comes through the constructor).

System.out.println(newGrade);
newGrade = grade;
System.out.println(grade);

Output shows newGrade = 1 (or whatever is selected) but grade = 0

I'm not sure if its something simple or something i've overlooked but I would appreciate any tips.

2
  • you are setting grade's value to the newGrade, you need to flid that statement: grade = newGrade; Commented Nov 29, 2013 at 14:42
  • grade should == 0 from what I see here... If you want grade to change you need to switch to grade = newGrade; Commented Nov 29, 2013 at 14:43

1 Answer 1

6

You assign from right to left. So what you do here is print out newGrade (which is 1) then assign it grade which is 0 then you print out grade which is still 0.

There are several problems here:

public int grade = 0;

This is trouble. The java guidelines state that you should use private variables (or no instance variables at all if possible). This way you can't make sure that some other (probably careless) programmer on your team does not tamper with grade.

newGrade = grade;

Since only copies of references are passed to methods/consturctors it is problematic if you try to reassign their values. It won't be reflected to the original object.

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

5 Comments

Oh my goodness thank you! I hadn't noticed i'd got them the wrong way around!
I'd say it's a higher risk that a careless programmer will tamper with the field than a malicious programmer. But by being careless, one could argue that this is in itself being malicious.
Sorry bad wording. It was supposed to be irony.
Done! Private variables seem to make compiling errors in this, fortunately its a solo mini project but i'm not entirely sure why this is.
They are making errors because you use those public fields elsewhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.