java可以在其他对象中调用父覆盖的方法而不是子类型吗? [英] Can java call parent overridden method in other objects but not subtype?

查看:20
本文介绍了java可以在其他对象中调用父覆盖的方法而不是子类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是工作的java代码

here is working java code

class Cup {
    public String sayColor() {
        return "i have a color .";
    }
}

class TCup extends Cup{
    public String sayColor(){
        System.out.println(super.getClass().getName());
        return super.sayColor()+"color is tee green.";
    }
}

class MyTCup extends TCup {
    public String sayColor(){
        System.out.println(super.getClass().getName());
        return super.sayColor()+"but brushed to red now!";
    }
}
class Test {
    public static void main(String[] args) {
        Cup c = new MyTCup();
        System.out.print(c.sayColor());
    }
}

并运行测试类打印

MyTCup
MyTCup
i have a color .color is tee green.but brushed to red now!

问题 1:在运行时,对象C的类型为MyTCup,但始终可以调用super方法.初始化对象后MyTCup内存中是否有方法栈,然后可以像代码一样在运行时调用?

question 1: At the runtime, the type of object C is MyTCup, but it can always call the super method. Is there a method stack in the memory within MyTCup after initializing the object, and then can call through at runtime like the code ?

问题 2:没有办法在其他对象中调用super方法.据我所知,C++ 可以随时转换为调用父方法.为什么它在 Java 中有所不同?

question 2: There is no way to call the super method in other objects. As I know ,c++ can cast to call parent method at any time. Why is it different in Java?

推荐答案

您不能在其他对象中调用 super 方法 - 这会违反封装.重点是对象控制其重写方法的作用.例如,您可能会覆盖集合的 add 方法以在某些情况下抛出异常,因此它可以确保仅将有效"项添加到集合中.如果调用者可以通过演员表绕过它,那将毫无意义!

You can't call the super method in other objects - that would violate encapsulation. The whole point is that the object controls what its overridden methods do. For instance, you might override a collection's add method to throw an exception in certain circumstances, so it could ensure only "valid" items got added to the collection. That would be pointless if callers could just bypass it with a cast!

对象为自己调用 super.foo() 的唯一原因是允许使用父实现来实现一个调用.这取决于类中的代码来确保它只明智地做到这一点.同样,以 add-in-a-collection 为例,如果集合覆盖了 add,它必须有 some 方法将已验证的项目添加到集合中,这它可以用 super.add().

The only reason an object gets to call super.foo() for itself is to enable one call to be implemented by using the parent implementation. It's up to the code in the class to make sure it only ever does that sensibly. Again, to take the add-in-a-collection example, if the collection overrides add it would have to have some way of adding the validated item to the collection, which it would do with super.add().

请注意,出于封装的相同原因,您可以调用您的父实现,而不是祖父实现 - 所以 super.foo() 是有效的,但是 super.super.foo() 不是.

Note that for the same reason of encapuslation, you can only call your parent implementation, not the grandparent implementation - so super.foo() is valid, but super.super.foo() isn't.

这篇关于java可以在其他对象中调用父覆盖的方法而不是子类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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