• Post Reply Bookmark Topic Watch Topic
  • New Topic

Constructors in Interfaces  RSS feed

 
sireesha vadlamani
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • 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
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • 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.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • 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.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • 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
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!