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

查看:157
本文介绍了为什么是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);
    }
}

现在我们可以添加任何我们喜欢的东西和不变量在$ code> RedItems 已损坏。

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

这有意义吗?

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

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