zoukankan      html  css  js  c++  java
  • ParentChildTest.java

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

    a) 左边的程序运行结果是什么?

     

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

    当子类与父类拥有一样的方法,并且让一个父类变量引用一个子类对象时,到底调用哪个方法,由对象自己的“真实”类型所决定,这就是说:对象是子类型的,它就调用子类型的方法,是父类型的,它就调用父类型的方法。

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

    如果子类与父类有相同的字段,则子类中的字段会代替或隐藏父类的字段,子类方法中访问的是子类中的字段(而不是父类中的字段)。

  • 相关阅读:
    CMDB 理论
    分布式
    闲着无聊 一个python的,三级菜单。装逼版。
    献上一段,派遣网易云音乐,音频的代码。
    redis 安装
    selenium之 chromedriver与chrome版本映射表(更新至v2.46)
    简单的爬虫
    anaconda使用方法
    crm开发之用户重置密码
    模块和包,logging模块
  • 原文地址:https://www.cnblogs.com/tangjindong/p/4966264.html
Copyright © 2011-2022 走看看