2

I'm having trouble finding information regarding this kind of subclassing/overriding in Java, which I see used a lot in Swing applications (event listeners and stuff like that):

// ...  
SomeClass foo = new SomeClass() { 
@Override
public String methodToOverride() { return ""; }
}

vs

class SubClass extends SomeClass {
@Override
public String methodToOverride() { return ""; }
}
// ...
SubClass foo = new SubClass();

Is the first case still a subclass of 'SomeClass', or is it the same type with an overridden method? In particular, what happens in the first case if inside methodToOverride() I call super.methodToOverride()? Will it call the original SomeClass' methodToOverride(), or SomeClass' parent methodToOverride()?

Edoz
  • 1,068
  • 1
  • 11
  • 16
  • [This Article](http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html) may help. – user3507600 Apr 09 '14 at 19:44
  • thanks. Part of the problem in fact was that I did not know the name of that 'trick' (anonymous subclass, now I renamed the question as well). – Edoz Apr 09 '14 at 19:48
  • @Edoz: A related example is seen [here](http://stackoverflow.com/a/8488735/230513). – trashgod Sep 14 '14 at 02:10

1 Answers1

2

Is the first case still a subclass of 'SomeClass', or is it the same type with an overridden method?

It is a subclass of SomeClass. And what do you mean by - "same type with overridden method". It doesn't make sense.

what happens in the first case if inside methodToOverride() I call super.methodToOverride()? Will it call the original SomeClass' methodToOverride(), or SomeClass' parent methodToOverride()?

It will call the method in SomeClass.

Basically the two approach works almost identically. You often use anonymous subclasses, when you only want to use them once. The difference is - you can't have constructors in anonymous subclasses, among others.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525