• 继承


        

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

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

    运行结果为

  • 相关阅读:
    【洛谷P3389】【模板】高斯消元
    【NOIP2016】提高组
    【NOIP2013】提高组
    【NOIP2012】提高组
    【NOIP2011】提高组
    【NOIP2010】提高组
    【NOIP2009】提高组
    【NOIP2008】提高组
    【NOIP2007】提高组
    【51nod 1189】阶乘分数——阶乘质因数分解
  • 原文地址:https://www.cnblogs.com/adret/p/9926197.html
Copyright © 2020-2023  润新知