• 继承与多态


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

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

    2.现在有三个类:

    class Mammal{}

    class Dog extends Mammal {}

    class Cat extends Mammal{}

    针对每个类定义三个变量并进行初始化

           Mammal m=null ;

    Dog d=new Dog();

    Cat c=new Cat();

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

           m=d;

           d=m;

           d=(Dog)m;

           d=c;

           c=(Cat)m;

    猜想:第二句将引起编译错误,因为将基类转化为子类需要强制类型转换、子类有的基类不一定有;第四句会引起编译时的错误,因为d,c不是同一个类的对象。不知那一句会在运行时出错

    运行后:最后一句在运行时出错,因为第一句将Dog类对象赋给Mammal对象m,再将m赋给c,就相当于将d赋给c,不同子类会出错。

    3.

    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);
        }
    }

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

         当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。如果子类与父类有相同的字段,则子类中的字段会代替或隐藏父类的字段,子类方法中访问的是子类中的字段(而不是父类中的字段)。如果子类方法确实想访问父类中被隐藏的同名字段,可以用super关键字来访问它。

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

  • 相关阅读:
    odoo国际化翻译
    Odoo创建基础模块和相关内容
    odoo权限管理(二.记录管理)
    推荐的 MongoDB 安装文档
    Python Spider 抓取今日头条街拍美图
    Python Spider 抓取猫眼电影TOP100
    如何选择 SQL Server 数据库跟操作系统版本
    Mongodb 折腾笔记
    MySQLReport
    kernel TCP time wait bucket table overflow
  • 原文地址:https://www.cnblogs.com/wxd136/p/7806702.html
Copyright © 2020-2023  润新知