一个关于JAVA继承与多态的实验题目

class Father{
int x=10,y=20; void speak(){
System.out.println("I am Father:"+"x="+x+":y="+y);
}
void calculate(String s) {
System.out.println(s+"x*y="+x+"*"+y+"="+x*y); } }
class Son extends Father{
int x=30; void speak(){ System.out.println("I am Son:"+"x="+x+":y="+y); }
void this_super(){ super.x=100; super.y=200; super.speak(); this.speak();
calculate("在子类中直接调用"); this.x=200;
this.y=300; } }
public class Demo2_3{
public static void main(String args[]){
Father father=new Father(); Son son=new Son();
System.out.println("----调用father对象speak()和calculate()结果-----"); father.speak();
father.calculate ("用father对象调用计算"); System.out.println("----调用son对象speak方法-----"); son.speak();
System.out.println("----调用son对象的修改数据方法-----"); son.this_super();
System.out.println("----调用father对象计算方法-----"); father.calculate("修改后用father对象调用"); System.out.println("----调用son对象计算方法-----"); son.calculate("修改后用son对象调用");
System.out.println("I am main:"+"son.x="+son.x+":son.y="+son.y); } }
【思考】
①子类Son中隐藏了父类Father那个变量?覆盖了那个方法?
②在子类Son方法void this_super()中,语句super.speak();this.speak();各有何作用? 输出什么结果?
③在子类Son方法void this_super()中,语句super.x=100; super.y=200; 修改的是哪个类x,y值?之后用什么方法验证的,结果应是什么?
④在子类Son方法void this_super()中,语句x=200; y=300; 修改的是哪个类x,y值?
⑤用对象father.speak()和son.speak()与类定义中的super.speak();this.speak();有何不同?

第1个回答  推荐于2016-06-08
①隐藏了变量y;重写了 speak()方法;
②分别调用基类和子类的speak()方法。super.speak()输出:I am Father:x=100:y=200;this.speak()输出I am Son:x=30:y=200;
③修改的父类x,y值。son.this_super() calculate("在子类中直接调用")验证,输出:在子类中直接调用x*y=100*200=20000;
④修改子类x,y;
本回答被提问者和网友采纳
第2个回答  2015-10-09
别人的思考不能加深你的理解。追问

才学Java几周,遇到这个题目不知道怎么解,但又是老师布置的作业,实在是被迫无奈才来提问的,你说的我又何尝不明白呢。还是谢谢你

相似回答