Moon
Moon

Reputation: 313

How to change values of a class instance with methods?

I have a class named Time with attributes Hour, Min and Sec:

class Time {
  private int Hour;
  private int Min;
  private int Sec;
}

a constructor:

public Time(int h, int m, int s){
    Hour = h;
    Min = m;
    Sec = s;
}

and an instance time1 of the Time class:

Time time1 = new Time(12, 34, 52);

I wanted to create a method inside that will sum to the Hour attribute of time1 instance and return me the result in Time type, but when I try this it gives me the "Type mismatch: cannot convert from int to Time" error:

     public Time Add(int hrs){
     return Hour + hrs;
 }

what am I doing wrong here?

Upvotes: 1

Views: 176

Answers (3)

Nowhere Man
Nowhere Man

Reputation: 19545

You seem to be looking for an instance method in Time class however, implementations may vary:

  • Mutate inner state of Time instance -- similar to a setter, returning reference to this
// mutate current instance:
class Time {
    public Time addHours(int hours) {
        this.Hours += hours;
        return this;
    }
}

Usage:
Time time1 = new Time(12, 34, 52);
time1.addHours(2); // time1.Hour becomes 14
  • Immutable implementation -- create new instance of time using its Hour and hours
// mutate current instance:
class Time {
    public Time addHours(int hours) {
        return new Time(Hour + hours, Min, Sec);
    }
}

// Usage:
Time time1 = new Time(12, 34, 52);
Time time2 = time1.addHours(2); // time1.Hour remains 14

Upvotes: 1

Ahmed
Ahmed

Reputation: 581

In the method return type you put Time but you are returning Hour(Type=int) + hrs(Type=int) which is their sum and it is also of type int. That's why you are getting the Type mismatch error

Upvotes: 0

azro
azro

Reputation: 54148

You need to instanciate a new Time object

public Time Add(int hrs){
    return new Time(this.Hour + hrs, this.Min, this.Sec);
}

Also java naming convention, is lowerCamelCase for methods and attributs so hour, min, sec and add

Upvotes: 5

Related Questions