Nick
Nick

Reputation: 205

Access modifiers

I'm new to Java and OOP and I would need some help with understading a few things. Say you have the following class:

public class NewClass {
    private long time;

    public NewClass () {
      time = 0;
    }

    public NewClass (long time) {
      this.time = time;
    }

    public long GetAsMs () {
      return time;
    }

    public boolean isGreaterThan(NewClass span) {
      return GetAsMs() > span.GetAsMs();
    }

I know that If I make a new instance of this class I will have an object containing the field/variable time and associated methods. I don't understand what is the method isGreaterThan exactly doing and how do I call it. Aren't these two "variables" that it is comparing always exactly the same?

Upvotes: 0

Views: 95

Answers (1)

Maroun
Maroun

Reputation: 96018

They might be different, note the constructor that accepts a parameter:

public NewClass (long time) {
      this.time = time;
}

If you construct two objects:

NewClass xObj = new NewClass(12345678910);
NewClass yObj = new NewClass(12345678919);

Now xObj.isGreaterThan(yObj) will return false. Why? Let's see what's happening there:

isGreaterThan is applied on xObj object, which has the class member time that has the value 12345678910. You're passing yObj that has it's own time, which has the value 12345678919 - And they are different, GetAsMs will return two different results when applied on different objects.

Upvotes: 2

Related Questions