为什么是 super.super.method();在 Java 中不允许? [英] Why is super.super.method(); not allowed in Java?

查看:37
本文介绍了为什么是 super.super.method();在 Java 中不允许?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了 这个问题 并认为如果有人可以写的话,这很容易解决(不是说没有它就无法解决):

I read this question and thought that would easily be solved (not that it isn't solvable without) if one could write:

@Override
public String toString() {
    return super.super.toString();
}

我不确定它在很多情况下是否有用,但我想知道为什么它没有用,以及在其他语言中是否存在类似的东西.

I'm not sure if it is useful in many cases, but I wonder why it isn't and if something like this exists in other languages.

大家怎么看?

澄清一下:是的,我知道,这在 Java 中是不可能的,我并没有真正想念它.这不是我期望的工作,并且对编译器错误感到惊讶.我只是有这个想法并喜欢讨论它.

To clarify: yes I know, that's impossible in Java and I don't really miss it. This is nothing I expected to work and was surprised getting a compiler error. I just had the idea and like to discuss it.

推荐答案

它违反了封装.您不应该能够绕过父类的行为.有时能够绕过您自己 类的行为(尤其是在同一方法中)而不是您的父类的行为是有意义的.例如,假设我们有一个基本的项目集合",一个表示红色项目集合"的子类和一个表示大红色项目集合"的子类.具有以下意义:

It violates encapsulation. You shouldn't be able to bypass the parent class's behaviour. It makes sense to sometimes be able to bypass your own class's behaviour (particularly from within the same method) but not your parent's. For example, suppose we have a base "collection of items", a subclass representing "a collection of red items" and a subclass of that representing "a collection of big red items". It makes sense to have:

public class Items
{
    public void add(Item item) { ... }
}

public class RedItems extends Items
{
    @Override
    public void add(Item item)
    {
        if (!item.isRed())
        {
            throw new NotRedItemException();
        }
        super.add(item);
    }
}

public class BigRedItems extends RedItems
{
    @Override
    public void add(Item item)
    {
        if (!item.isBig())
        {
            throw new NotBigItemException();
        }
        super.add(item);
    }
}

那很好 - RedItems 总是可以确信它包含的项目都是红色的.现在假设我们能够调用 super.super.add():

That's fine - RedItems can always be confident that the items it contains are all red. Now suppose we were able to call super.super.add():

public class NaughtyItems extends RedItems
{
    @Override
    public void add(Item item)
    {
        // I don't care if it's red or not. Take that, RedItems!
        super.super.add(item);
    }
}

现在我们可以添加任何我们喜欢的东西,RedItems 中的不变量被破坏了.

Now we could add whatever we like, and the invariant in RedItems is broken.

有意义吗?

这篇关于为什么是 super.super.method();在 Java 中不允许?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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