When I was looking at a question, I thought that using the super.super.method() like the code below would solve it easily.
@Override
public String toString() {
return super.super.toString();
}
I don't know if super.super.method() is useful in many cases, but I suddenly wondered. Why isn't this working? And can't you do this in other languages? If anyone knows, please explain.
java superclass
super.super.method() violates encapsulation. The super.super.method bypasses the processing of the parent class, which creates many problems.
For example, suppose you have a code that collects items as follows:
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);
}
}
It's okay up to here. If you look at BigRedItems, RedItems always have a red color because they are processed by RedItems in super.add(item) and if the item is not red, they will make an exception. And if super.super.add(); is now possible
public class NaughtyItems extends RedItems
{
@Override
public void add(Item item)
{
// No exceptions are made whether the item is red or not.
super.super.add(item);
}
}
RedItems are not treated as exceptions, so there is no point in inheriting them.
© 2024 OneMinuteCode. All rights reserved.