Win a copy of Microservices Testing (Live Project) this week in the Spring 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

Constructors in Interfaces

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can i use constructors in an interface?

interface AI
{
public abstract AI();
public abstract void hello();
}
Output: i got the error as the method AI() should have return type.
explain it clearly thanks
 
Marshal
Posts: 76061
362
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please have a look at the Java Language Specification, which will tell you what sort of members you can have in interfaces. Try §9.1.4 or §9.2. That is the Java8 version, so it may include default methods. Try ctrl‑F‑“constructor”

Even if you can have a constructor in an interface, you must not declare it abstract.
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As for why not...a constructor is there to initialise the state of an object. An interface has no state to initialise, so there is no reason for there to be one.
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

sireesha vadlamani wrote:Can i use constructors in an interface?


No, but what you can do is create an anonymous class (which is actually an object), via the "default" constructor, which looks somewhat similar, viz:

private AI anonymousAI = new AI() {
  public void hello() { System.out.println("Hello"); }
};  
// (note the ';')

And just FYI, another convention for you: The 'public and 'abstract' qualifiers for methods are redundant, because interface methods are both public and abstract by default; however, many programmers (including me) include the 'public', but rarely the 'abstract'.

But don't worry about it too much, what you've put is just fine.

HIH

Winston
reply
    Bookmark Topic Watch Topic
  • New Topic