class Sum {
int n;
float f() {
float sum=0;
for(int i=1;i<=n;i++)
sum=sum+i;
System.out.println(“()=”+n);
return sum;
}
}
class Average extends Sum {
int n;
float f() {
float c;
super.n=n;
c=super.f();
System.out.println(“f()=”+c);
return c/n;
}
float g() {
float c;
c=super.f();
System.out.println(“g()=”+c);
return c/2;
}
}
public class Example5_7 {
public static void main(String args[]) {
Average aver=new Average();
aver.n=100;
}
}
float resultTwo=aver.g();
float resultOne=aver.f();
/*System.out.println("resultTwo="+resultTwo);
System.out.println("resultOne="+resultOne);*/
}
}
输出结果为
()=0
g()=0.0
()=100
f()=5050.0
可见程序先调用了g()函数的情况下,n=0,所以第一次输出为0
第二次调用f()函数,n=100,所以输出为5050.0