03-继承与多态

一、动手实验:继承条件下的构造方法调用

class Grandparent

{

    public Grandparent()

  {

         System.out.println("GrandParent Created.");

}

    public Grandparent(String string)

{

         System.out.println("GrandParent Created.String:" + string);

 }

}

class Parent extends Grandparent

{

    public Parent()

 {

         super("Hello.Grandparent.");

         System.out.println("Parent Created");

       // super("Hello.Grandparent.");

  }

}

class Child extends Parent

{

    public Child()

 {

        System.out.println("Child Created");

  }

}

public class TestInherits

{

    public static void main(String args[])

 {

         Child c = new Child();

  }

}

运行结果:

Super在前:GrandParent Created.String:Hello.Grandparent.

Parent Created

Child Created

Super在后直接报错

所以通过 super 调用基类构造方法,必须是子类构造方法中的第一个语句。

二、方法覆盖要求子类与父类的方法一模一样,否则就是方法重载(overload)!

请自行编写代码测试以下特性(动手动脑):

在子类中,若要调用父类中被覆盖的方法,可以使用super关键字。

public class Num {

 

public static void main(String[] args) {

// TODO Auto-generated method stub

N a=new N(0);

Num2 b=new Num2(1);

}

 

}

 

class N{

N(int i){

 System.out.println(i);

}

}

class Num2 extends N{

Num2(int a){

super(a);

}

}

运行结果:

0

1

三、

public class ParentChildTest {

public static void main(String[] args) {

Parent parent=new Parent();

parent.printValue();

Child child=new Child();

child.printValue();

 

parent=child;

parent.printValue();

 

parent.myValue++;

parent.printValue();

 

((Child)parent).myValue++;

parent.printValue();

 

}

}

 

class Parent{

public int myValue=100;

public void printValue() {

System.out.println("Parent.printValue(),myValue="+myValue);

}

}

class Child extends Parent{

public int myValue=200;

public void printValue() {

System.out.println("Child.printValue(),myValue="+myValue);

}

}

 

1.   程序运行结果是什么?

Parent.printValue(),myValue=100

Child.printValue(),myValue=200

Child.printValue(),myValue=200

Child.printValue(),myValue=200

Child.printValue(),myValue=201

 

2.   你如何解释会得到这样的输出?

子类对象会将父类的对象进行覆盖

3.   计算机是不会出错的,之所以得到这样的运行结果也是有原因的,那么从这些运行结果中,你能总结出Java的哪些语法特性?

对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。

如果子类与父类有相同的字段,则子类中的字段会代替或隐藏父类的字段,子类方法中访问的是子类中的字段(而不是父类中的字段)。如果子类方法确实想访问父类中被隐藏的同名字段,可以用super关键字来访问它。

如果子类被当作父类使用,则通过子类访问的字段是父类的!

posted @ 2021-10-30 10:41  zrswheart  阅读(44)  评论(0编辑  收藏  举报