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();有何不同?
才学Java几周,遇到这个题目不知道怎么解,但又是老师布置的作业,实在是被迫无奈才来提问的,你说的我又何尝不明白呢。还是谢谢你