Class Time In Java POO

package time; /** * * @author Geek */ public class Time { //atributos private int hour; private int minute; private int second; //constructores public Time(){ //hour = minute = second = 0; } public Time(int hour, int minute, int second){ setHour(hour); setMinute(minute); setSecond(second); } public Time(Time time){ this.hour = time.hour; this.minute = time.minute; this.second = time.second; } public int getHour(){ return hour; } public int getMinute(){ return minute; } public int getSecond(){ return second; } public void setTime(int hour, int minute, int second){ setHour(hour); setMinute(minute); setSecond(second); } public void setHour(int hour){ this.hour = hour>=0 && hour<24?hour:0; } public void setMinute(int minute){ this.minute = minute>=0 && minute<60?minute:0; } public void setSecond(int second){ this.second = second>=0 && second<60?second:0; } public String printMilitary(){//08:41:16 a.m. return (hour<10?"0"+hour:hour)+":"+(minute<10?"0"+minute:minute) +":"+(second<10?"0"+second:second); } @Override public String toString(){ String s = ""; if(hour<12){ s+=hour<10?"0"+hour:hour; }else{ int h = hour -12; s+=h<10?"0"+h:h; } s+=":"+(minute<10?"0"+minute:minute) +":"+(second<10?"0"+second:second); if(hour<12){ s+= " a.m."; }else{ s+=" p.m."; } return s; } public static void main(String[]args){ Time breakTime = new Time (10,10,0);//Aqui se cambia la hora en formato de 24 horas System.out.println("Today the break is at "+breakTime); } }

1 Response

If you permit a suggestion or two.
I would make each attribute final, and made possible to be create only by its constructor or create some kind of static factory [Effective Java, Item 1]. Of course making the attributes final you would get rid of this public setters. That way you would ensure that the "breakTime" would not change in the application runtime (of course if this is your intention).
It is just a suggestion :). In java it's always good to make the attributes final for thread safaty and to ensure that it will not change throughout the application runtime (if it's your intention).
Best Regards ;D

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.