java继承与多态

继承与多态

动手动脑

1,继承条件下的构造方法的调用

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

2,为什么子类的构造方法在运行之前,必须采用父类的构造方法?能不能反过来?为什么?

构造方法是用来初始化变量,如果不调用父类的构造方法,而是直接构造子类的构造方法,则会出现未初始化变量的错误。

3,class A{

}

 public class part1{

     public static void main(String[] args){

     System.out.println(new A());

     }

 }

运行结果为:

exercise.A@15db9742

当为指明该类所继承的父类时,所有的类继承的都是object类,所以初始化时调用了object类中的构造方法,返回输出该对象的哈希值,并用16进制表示。

4,public class Fruit

{

public String toString()

{

return "Fruit toString.";

}

public static void main(String args[])

{

Fruit f=new Fruit();

System.out.println("f="+f);

// System.out.println("f="+f.toString());

}

}

运行结果为:

f=Fruit toString.

  “+”运算中,当任何一个对象与一个String对象,连接时,会隐式地调用其toString()方法,默认情况下,此方法返回“类名 @ + hashCode”。为了返回有意义的信息,子类可以重写toString()方法。

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

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

package exercise;

class A{

public void m(){

System.out.println("父类方法");

}

}

class B extends A{

//super();

public void m(){

//System.out.println("子类方法");

super.m();

}

}

 public class part1{

     public static void main(String[] args){

     B b=new B();

     b.m();

     }

 }

运行结果为:

父类方法

6,类型转换

下列语句哪一个将引起编译错误?为什么?哪一个会引起运行时错误?为什么?

m=d;

d=m;

d=(Dog)m;

d=c;

c=(Cat)m;

先进行自我判断,得出结论后,运行TestCast.java实例代码,看看你的判断是否正确。

自我判断:

d=m;d=c;会与引起编译错误

父类对象不能直接赋给子类对象,子类对象之间也不能相互赋值,只有通过强制转换才能。

运行代码结果显示:

d=m;d=c;会与引起编译错误

判断正确

7,

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.   左边的程序运行结果是什么?

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

3.   计算机是不会出错的,之所以得到这样的运行结果也是有原因的,那么从这些运行结果中,你能总结出Java的哪些语法特性?请务必动脑总结,然后修改或编写一些代码进行测试,验证自己的想法,最后再看 后面的PPT给出的结论。

运行结果:

Parent.printValue(),myValue=100

Child.printValue(),myValue=200

Child.printValue(),myValue=200

Child.printValue(),myValue=200

Child.printValue(),myValue=201

当把子类对象赋给父类对象后,父类对象调用的方法全是子类中的方法,此时parent.myValue++所改变的数值只是父类中myValue的值,所以结果仍未子类中myValue的数值,而((Child)parent).myValue++改变的则是子类中myValue的值,所以输出201。

总结:

对象调用哪个方法,由这个对象的类型决定。

原文地址:https://www.cnblogs.com/news1997/p/7809900.html