• Post Reply Bookmark Topic Watch Topic
  • New Topic

Instansiate an abstract method works if method is passed as argument. Why?  RSS feed

 
Sven Sylta
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! This is an old exam-question I'm trying to understand. The task is to find out what's printing out. I know that it is not possible to instantiate an abstract method but why does it work when a method is passed as an argument?

These lines occur in the main method in the program below and they really confuses me. Can someone explain exactly what happens here? Thanks.



The program starts here:

 
Stuart A. Burkett
Ranch Hand
Posts: 679
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's known as an anonymous class
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sven Sylta wrote:Hi! This is an old exam-question I'm trying to understand. The task is to find out what's printing out. I know that it is not possible to instantiate an abstract method but why does it work when a method is passed as an argument?

It is also important to get the terminology correct. You can never 'instantiate a method' abstract or not, because only instances of Classes can be instantiated. You also can't pass a method as an argument in Java.

If I try to rephrase the question so it uses the correct terms, it sort of answers itself:
'I know that it is not possible to instantiate an abstract class but why does it work when you supply a method implementation?'

That may be leading because I know the answer, but I can't think of a way to ask the question that doesn't provide the answer when I use the correct terms. Stuart gave you a link describing what the structure is, but why it works is because you are extending the Class C with a new one and providing a method which implements the last abstract method in C - so this new unnamed class (thus called anonymous) has no abstract methods and can be instantiated.
 
Sven Sylta
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great answers, thank you.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!