zoukankan      html  css  js  c++  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);
        }
    }

    结果:

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

    父类型的方法。

    这个特性实际上就是面向对象“多态”特性的具体表现。如果子类与父类有相同的字段,则子类中的字段会代替或隐藏父类的字段,子类方法中访问的是子类中的字段(而不是父类中的字段)。如果子类方法确实

    想访问父类中被隐藏的同名字段,可以用super关键字来访问它。

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

  • 相关阅读:
    linux shell在while中用read从键盘输入
    ubuntu14.04折腾迅雷xware
    select与epoll分析
    ubuntu 14.04下练习lua
    C++中的重载、覆盖、隐藏
    删除ubuntu旧内核
    fcntl函数加文件锁
    系统中断与SA_RESTART
    linux使用共享内存通信的进程同步退出问题
    leetcode-easy-others-268 Missing Number
  • 原文地址:https://www.cnblogs.com/leity/p/9903969.html
Copyright © 2011-2022 走看看