为什么在 OOP 中这样做 [英] Why this in OOP

查看:67
本文介绍了为什么在 OOP 中这样做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Parent {

    private int var = 1;

    public int getVar() {
        return var;
    }

    public void setVar(int var) {
        this.var = var;
    }

}

class Child extends Parent {

    private int var = 2;

    public int getVar() {
        return var;
    }

    public void setVar(int var) {
        this.var = var;
    }

}

现在,在测试时,我们得到 2.

And now, when testing it, we get 2.

Child child = new Child();
Parent parent = (Parent)child;
System.out.println(parent.getVar());

我正在明确地将子对象转换为父对象并明确表达我的意图为什么那么当我做 parent.getVar() 时我得到 2 ?

I am casting the child object to a Parent explicitly and making my intentions clear why then when i do parent.getVar() i get 2 ?

推荐答案

Child child = new Child();
Parent parent = (Parent)child;

您只是使用超类引用来指向.您的对象仍然属于 Child 类并且永远不会改变.所以你总是会得到 2.

You are simply using a super class reference to point. Your object is still of class Child and that will never change. So you would always get 2.

所以当你打电话

System.out.println(parent.getVar());

在编译时检查 getVar() 是否存在于引用类 Parent 中,这是真的.所以它编译.在运行时它知道实际对象的类,即Child并执行相应的方法.

at compile time it checks whether getVar() is present in class of reference Parent which is true. So it compiles. At runtime it knows the class of actual object which is Child and executes corresponding method.

这篇关于为什么在 OOP 中这样做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆