Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading