Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)

I was wondering  what 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.

What do you guys think?

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.

1 Answer

0 votes
by (46k points)

It disrupts encapsulation. You shouldn't be capable to neglect the parent class's performance. It makes discernment to sometimes be able to bypass our personal class's behavior (especially from inside the same course) but not your parents. For example, assume we have a base "set of items", a subclass describing "a collection of red items" and a subclass of that designing "a collection of big red items". It makes discernment to possess:

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

    }

}

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

    }

}

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

Related questions

0 votes
1 answer
asked Sep 10, 2019 in Java by Nigam (4k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...