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关键字来访问它。

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

  • 相关阅读:
    Autofac 学习简易教程随笔(一)
    实现Entity Framework SQLite Code First 开发
    Entity Framework SQLite 开发及实现简单的自定义Migration Engine
    MSSQLServer和SQL Server Express、LocalDB的区别
    .gitignore文件
    Entity Framework MSSQL Code First 开发
    页面为要加<!DOCTYPE html>
    数字图像处理(下)
    数字图像处理(上)
    列表
  • 原文地址:https://www.cnblogs.com/leity/p/9903969.html
Copyright © 2011-2022 走看看