I've currently been reading the documentation 3 times now, and I am having a hard time applying what is written to my own simple program. I'm trying to understand on a fundamental level why exactly I am writing p.add(v);
in my code below.
I declare an object p
, and an object v
with the values of 5 and 17 respectively. My method add
then adds the two values together. I takes on the argument v
so I understand that the object v
has to be in the brackets of add(v)
when I refer to it in my main method. However I'm having a hard time explaining in words why I need to call on the method add
with respect to p
here. Isn't p
also an argument like v
? Why can't I just change my method to be:
public void add(Positive v, Positive p)
And then call it by saying add(v,p);
?
According to the java documentation, I need to call on a method when the object is outside of my class? But everything here is inside my class? So I'm not sure what it is exactly that they're trying to say in the documentation.
public class Positive {
public static void main(String[] args) {
Positive p = new Positive(5);
Positive v = new Positive(17);
p.add(v);
System.out.println(p.get());
}
private int n;
public Positive(int n) {
this.n = n;
}
public void add(Positive v)
{
this.n += v.get();
}
public int get() {
return n;
}
}