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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With