Why increment method does not increment the object parameter value? | SoloLearn: Learn to code for FREE!

+1

Why increment method does not increment the object parameter value?

Hi everyone, Could anyone explain me the reason why incrementA method does not increment the parameter value here? I changed method type, method parameter type but the result does not change. public class Program { public int a; private double b; public Program(int first, double second) { this.a = first; this.b = second; } public static void incrementA(int first) { first = first + 1; } public static void incrementA(double second) { second = second + 1; } public static void incrementBoth(Program obj) { obj.a = obj.a + 1; obj.b = obj.b + 1; } public static void main(String[] args) { Program myObj1 = new Program(10, 15.6); Program myObj2 = new Program(10, 20.5); incrementA(myObj1.a); System.out.println(myObj1.a); } }

5/11/2019 8:30:38 AM

Derya A.

5 Answers

New Answer

+3

You do not return your result. Your parameter is passed by value, incemented in your function, and destroyed after leaving it. And you should rewrite your code! Attributes should not be manipulated from outside! Increment functions should not be static! And if you manipulate attributes within them, use the attributes: public void IncrementA() { this.a++; } public void IncrementB() { this.b++; } public void IncrementAB() { this.IncrementA(); this.IncrementB(); } And then: myObj1.IncrementA();

+6

Derya A. Your class has the variables a and b. Now look in your increment method: first = first + 1; First ist the variable from the method and not the variable from your object. And I think your increment method don't need parameters. --> a += 1 or a++ --> b += 1 or b++ Daniel Adam What do you know about OOP and/or how much do know about OOP? It is wrong, that there is nothing object oriented in this code. It is not perfect but you have a class, with attributes and methods, there is a constructor...

+2

Thank you Denise, it is clear now

+1

This line is just a question for passing object oriented programming class. Therefore I am trying to understand the structure rather than do’s and not to do’s. Thank you for your answer anyway.

-1

There is nothing object oriented in your code. Just saying.