Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Creating an object of Interface

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everyone,

Could anyone please look into the code below?



The is compiling and the output is 10.

My Question: Can we create an instance of an interface which has a default method?
e.g:
Jumpable tc = new Jumpable(){};

Thanks,
Prabal.
 
Marshal
Posts: 25682
69
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Prabal Nandy wrote:My Question: Can we create an instance of an interface which has a default method?



No, you can't.

e.g: Jumpable tc = new Jumpable(){};



Here you are creating an instance of an anonymous inner class which implements Jumpable.

If you try it without the {} at the end, which is what makes it an anonymous inner class, then you would have a proper line of code which would answer your question.
 
Bartender
Posts: 4006
156
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And perform some more experiments like:

Jumpable tc = new TestCase();
Movable tnc = new TestCase();
change 'default' to 'static'
et cetera

and try to explain all the outcomes you see.
 
Prabal Nandy
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Paul and Piet!
I came to know the fact later.
 
Sheriff
Posts: 11604
178
Hibernate jQuery Eclipse IDE Spring MySQL Database AngularJS Tomcat Server Chrome Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Disclaimer (only for completeness): anonymous inner classes are not on the OCAJP exam, it's one of the exam topics of the OCPJP exam.
 
I think she's lovely. It's this tiny ad that called her crazy:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic