I have 2 classes . The one is about a 24 hour clock and the second one is a subclass of the first and is a 12 hour clock.
To convert the new time in second class i need to change the value of the first class. But i can’t do that.
I am talking about “h” variable
Specifically…
class Clock{
public int h, m , s;
public String a,b,c;
public void setHour(int hour){
this.h = hour;
}
public void setMin(int min){
this.m = min;
}
public void setSec(int sec){
this.s = sec;
}
public void tick(){
if(h != 23){
if(m == 59 && s==59){
m = 0;
s=0;
h++;
}
else if(m != 59 && s == 59){
m++;
s=0;
}
else if ( m != 59 && s != 59){
s++;
}
else if( m == 59 && s!=59){
s++;
}
}
else if(h == 23 && m == 59 && s !=59){
s++;
}
else if(h == 23 && m!=59 && s == 59){
s=0;
s++;
m++;
}
else if(h == 23 && m!=59 && s!=59){
s++;
}
else if(h == 23 && m == 59 && s == 59){
s = 0;
m =0;
h = 0;
}
}
public String toString(){
a = "";
b = "";
c = "";
if (h < 10)
a = "0";
if (m <10 )
b = "0";
if (s <10)
c = "0";
return a+h+":"+b+m+":"+c+s;
}
}
class AMPMClock extends Clock{
Clock clock2 = new Clock();
public void setAMPM(boolean yes){
if(yes == true){
**clock2.h = clock2.h - 12**;
}
}
}
Your
AMPMClockshould either just extendClockor just use it. But you are trying to combine them both as follows:Either extend:
Because, the public accesor methods are inherited, you can invoke getter/setter methods on
this. e.g.this.getHour().Or use it but don’t extend:
Here, instead of
thisuseclock2. e.g.clock2.getHour().But, you need to make all the instance members private (they should not to be public). And make corresponding public getter/setter for all of them.
As suggested by dasblinkenlight:
It would be better to have an abstract class:
And two different concrete classes:
and