问题遇到的现象和发生背景
JAVA:在subclass中使用getter时报错java.lang.NoSuchMethodError
在下面subclass执行System.out.println(ac1.getHours());这个语句的时候
用代码块功能插入代码,请勿粘贴截图
下面这个是报错的subclass
public class AlarmClock extends Clock{
// Alarm's hours, minutes, sound
private int alarmHours;
private int alarmMinutes;
String alarmSound;
// Test Client
public static void main(String[] args) {
AlarmClock ac1 = new AlarmClock(5, 58, 6, 0);
ac1.tick();
ac1.tick(); // Beep beep beep beep!
System.out.println(ac1); // 06:00
System.out.println(ac1.getHours());
}
//Constructor
public AlarmClock(int h, int m, int alarmHours, int alarmMinutes) {
super(h, m);
this.alarmHours = alarmHours;
this.alarmMinutes = alarmMinutes;
this.alarmSound = "Beep beep beep beep!";
}
}
Superclass中的内容
public class Clock {
private int hours;
private int minutes;
//Constructor
public Clock(int h, int m) {
this.hours = h;
this.minutes = m;
}
public String toString() {
String a;
if (hours < 10) {
a = "0" + hours;
}
else {
a = hours + "";
}
a = a + ":";
if (minutes < 10) {
a = a + "0" + minutes;
}
else {
a = a + minutes;
}
return a;
}
//Getter
public int getHours() {
return this.hours;
}
public int getMinutes() {
return minutes;
}
运行结果及报错内容
我的解答思路和尝试过的方法
但我也把其中与报错相关的代码搬出来放到另一个superclass和subclass中时,程序并不会报错
Subclass:
public class simplemath1 extends simplemath{
private int alarmHours;
private int alarmMinutes;
public simplemath1(int h, int m, int alarmHours, int alarmMinutes) {
super(h, m);
this.alarmHours = alarmHours;
this.alarmMinutes = alarmMinutes;
}
public static void main(String[] arg) {
simplemath1 a = new simplemath1(6, 36, 6, 70);
System.out.println(a.getHours());
}
}
Superclass:
public class simplemath {
private int hours;
private int minutes;
public simplemath(int h, int m) {
this.hours = h;
this.minutes = m;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
simplemath a = new simplemath(5, 36);
}
public int getHours() {
return hours;
}
}
这样的程序反而可以正常运行,结果是:
我想要达到的结果
为什么会出现这样的问题呢?我该怎么解决这个问题?这个报错java.lang.NoSuchMethodError在这里具体指什么呢?
谢谢