A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© zhaoalei 中级黑马   /  2014-7-21 21:22  /  1392 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

class  Parent
{
    public void method1()
       {
               System.out.println("parent 1");
               this.method2();
        }
    public void method2()
        {
              System.out.println("parent 2");
         }
}
class Son extends Parent
{
       public void method1()
         {
               super();
                 System.out.println("son 3");
                 this.method2();

          }
      public void method2()
        {
              System.out.println("son 4");
         }
}
class Dashen
{
   public static void  main(String[] arg)
      {
        Son s=new Son();
        s.method1();
       }
}

评分

参与人数 1技术分 +1 收起 理由
Doraemon + 1

查看全部评分

3 个回复

正序浏览
注释为这个,并且super(),书写有错误.先已经改正.

class  Parent
{
    public void method1()
       {
               System.out.println("parent 1");
               this.method2();//调用父类中method2的方法
        }
    public void method2()
        {
              System.out.println("parent 2");
         }
}
class Son extends Parent
{
               
       public void method1()
         {  
                                super.method1();//调用父类
                 System.out.println("son 3");
                 this.method2();//调用子类的method2

          }
      public void method2()
        {
              System.out.println("son 4");//将父类里面的method2进行重写.
         }
}
class Dashen
{
   public static void  main(String[] arg)
      {
        Son s=new Son();
        s.method1();
       }
}

/*输出结果
parent 1
son 4
son 3
son 4
*/
回复 使用道具 举报
super()代表的是父类的无参数的构造方法,你是想调用method1(),应该是super.method1().
修改程序
class  Parent
{
    public void method1()
       {
                        System.out.println("parent 1");
                        this.method2();
        }
    public void method2()
        {
                        System.out.println("parent 2");
         }
}
class Son extends Parent
{
        public void method1()
    {
                super.method1();
                System.out.println("son 3");
                this.method2();

    }
      public void method2()
        {
              System.out.println("son 4");
         }
}
class Dashen
{
   public static void  main(String[] arg)
      {
        Son s=new Son();
        s.method1();
       }
}
但是这里面还有覆盖存在
回复 使用道具 举报
子类复写了父类的两个方法。
子类调用method1 的时候,super调用的是父类的内容,因而输出“parent 1”。
继而执行this.method2,this代表你创建的对象,是s,此时method2已经被复写,所以是“son4”。
super.method1执行完毕,然后是System.out.println("son 3"),所以输出“son 3”。
最后执行method2,还是“son4”。

评分

参与人数 1技术分 +1 收起 理由
Doraemon + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马