gumuyang
发贴: 21
积分: 0
|
于 2007-01-31 09:40
class Father{ int x=0,y=0; Father(){ System.out.println("now is in Father's constructor"); } Father(int x,int y){ this.x = x; this.y = y; } public void print(){ System.out.println("x="+x+";y="+y); } } class Son extends Father{ Son(){ System.out.println("now is in Son's constructor"); } Son(int x,int y){ super(x,y); //this(); //调用自己的构造器 } public void print(){ super.print(); System.out.println("My name is son!"); } } public class Example4_13{ public static void main(String[] args){ //通过默认构造器创建实例 Son s = new Son(); s.print(); //通过其他构造器创建实例 Son f = new Son(10,20); f.print(); } }
结果显示如下: now is in Father's constructor now is in Son's constructor x=0;y=0 My name is son! x=10;y=20 My name is son!
我对程序运作的认识如下: 从public class Example4_13{这一行开始是主程序 令我困惑的主要有两个问题:
一、子类继承父类时,为什么要把父类的所有程序段都执行一遍,而不是在s.print()只执行*.print()里的程序?我知道这是规范,但我很想知道为什么会这样规范,如果有人能描述一遍规范,我会非常感激!
二、从结果看来,好像父类和子类的内容是交替实现的,为什么不是先把父类的所有结果都实现一遍并显示,然后再显示子类的结果呢?
我知道这里新人很多,我也是其中一个,免不了又要给高手添麻烦。之前我也在这里静静地看过很多帖子,也下载了thinking in java,但作为只有薄弱的c语言基础的新人,第一章就让我看得云山雾罩,真的好希望身边有个高手,能边看边问,那该多好啊,我知道这很奢侈,只是说说心里话而已。
|