Monday 26 May 2014

Why is super.super.method(); not allowed in Java? (Child To Grandfather...LOL)


I have 3 classes they inherit from each other as follows:
A

B

C
Inside each class I have the following method:
protected void foo() {
...
}
Inside class C I want to call foo from class A without calling foo in B:
protected void foo() {
// This doesn't work, I get the following compile time error:
// Constructor call must be the first statement in a constructor
super().super().foo();
}

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);
}
}
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 whatever we like, and the invariant in RedItems is broken.
Does that make sense?


You can't even use reflection. Something like

Class superSuperClass = this.getClass().getSuperclass().getSuperclass();
superSuperClass
.getMethod("foo").invoke(this);
 
would lead to an InvocationTargetException, because even if you call the foo-Method on the superSuperClass, it will still use C.foo() when you specify "this" in invoke. This is a consequence from the fact that all Java methods are virtual methods.

Finally we have only one way: Child To Papa... And Papa To Grand Papa... 

1 comment:

  1. The King Casino Hotel | Jamul Casino & Spa
    The King Casino Hotel titanium flat iron is worrione set 1 mile south of Jamul https://jancasino.com/review/merit-casino/ Casino, 1 MPRC 출장안마 Blvd, Jamul, 메이저 토토 사이트 Georgia. View map. This casino offers a variety of gaming options including slots,

    ReplyDelete