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 的哪些语法特性?

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

  • 相关阅读:
    easyui-datetimebox设置默认时分秒00:00:00
    分页工具类的封装
    关于查询排序DTO的封装
    android签名生成和发布
    android httpclient 设置超时
    Eclipse 模拟http 请求插件Rest Client
    volley 发送post请求
    mac book 华为C8815不能debug
    android一些小技巧
    PS相关技术
  • 原文地址:https://www.cnblogs.com/tangjindong/p/4966264.html
Copyright © 2011-2022 走看看