《Java语言程序设计》继承与多态

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

调用运行 TestInherits.java 示例,观察输出,注意总结父类与子类之间构造方法的调用关系修改Parent构造方法的代码,显式调用GrandParent的另一个构造函数,注意这句调用代码是否是第一句,影响重大!

源代码:

package eg1;


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 调用基类构造方法,必须是子类构造方法中的第一个语句。

二、请自行编写代码测试以下特性(动手动脑): 在子类中,若要调用父类中被覆盖的方法,可以使用super关键字。

源代码:

package eg1;

class Parent
{
int x;
public Parent()
{

System.out.println("Parent Created1");
}
public void show(){
System.out.println("Parent Created2");
}

}

class Child extends Parent
{
int y;
public Child()
{

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

}
public void show(){
super.show();
System.out.println("Parent Created3");
}

}

public class TestInherits
{


public static void main(String args[])
{

Child c = new Child();
c.show();
}

}

运行结果:

三、运行以下测试代码

回答问题:

1. 左边的程序运行结果是什么? 2. 你如何解释会得到这样的输出? 3. 计算机是不会出错的,之所以得 到这样的运行结果也是有原因的, 那么从这些运行结果中,你能总 结出Java的哪些语法特性? 

答:

1. 源代码为:

package eg1;
public class TestInherits {
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);
}
}

运行结果为:

2.3.

当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。 这个特性实际上就是面向对象“多态”特性的具体表现。

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

原文地址:https://www.cnblogs.com/xiangyu721/p/11745556.html