Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use getter/setter methods in interface

Tags:

java

interface

My question is how can I write setter/getter methods and static fields in an interface and implement it in another class.

An example:

public interface MyInterface {
int number = 0;

public int setNumber(int num);{

 }
}

// Use it

public MyClass implements MyInterface{

 ...

public int setNumber(int num) {
   number = num;   // Error, Why?
 }
}

I get error on number = num but it get no error in the setName(...) method!

like image 938
Sajad Avatar asked Dec 14 '12 12:12

Sajad


1 Answers

Interface can not contain method body definition and field are public, final and static by default which normally use for constant declaration. It will be defined where you are going to implement this interface.

In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.

ref

But abstract class can contain concrete method as well as abstract method.

like image 197
Subhrajyoti Majumder Avatar answered Oct 24 '22 21:10

Subhrajyoti Majumder