我是一名Java初学者,我使用PHP,C++和Lua,并且从来没有遇到过这个问题,我只为了运动的缘故做了两个类Facto
和MyFacto
,第一个确实找到了阶乘,第二个应该通过增加而不是通过乘法来找到阶乘。不要责怪我愚蠢和毫无意义的代码,我只是测试并试图获得Java的窍门。java覆盖不工作
主营:
public class HelloWorld {
public static void main(String[] args) {
Facto fc = new Facto(5);
fc.calc();
System.out.println(fc.get());
MyFacto mfc = new MyFacto(5);
mfc.calc();
System.out.println(mfc.get());
}
}
Facto.java:
public class Facto {
private int i;
private int res;
public Facto(int i) {
this.i = i;
}
public void set(int i) {
this.i = i;
}
public int get() {
return this.res;
}
public void calc() {
this.res = this.run(this.i);
}
private int run(int x) {
int temp = 0;
if(x>0) {
temp = x + this.run(x-1);
}
return temp;
}
}
MyFacto.java:
public class MyFacto extends Facto {
public MyFacto(int i) {
super(i);
}
private int run(int x) {
int temp = 0;
if(x>0) {
temp = x * this.run(x-1);
}
return temp;
}
}
我想结果应该是15和120,但我得到15 15.为什么会发生?这与calc()
方法没有被覆盖有什么关系,它使用Facto
类的run()
方法?我怎样才能解决这个问题或者什么是正确的方式来重写这样的事情?
在两个类中将'private int run()'更改为'protected int run()'。 –
@GregKopff究竟在'Facto'类还是'MyFacto'中?我改变了他们两个,结果是15和0. –
,因为0 *任何= 0.即你的覆盖现在正常工作,工作逻辑。=) –