Sajad HTLO Sajad HTLO - 29 days ago 20
Java Question

use set/get methods in interface

I am new to Java (exactly one year!)

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

My code is like this: (brief!)

public interface myInterface{
int number=0;

public int setNumber(int num);{

}
}

// my class

public void myClass extends JFrame implements myInterface{

...

public int setNumber(int num){
number=num; // Error! Why? What I do?

}
}


In statement
number=num
it has error, but it has no error in setName method!

Answer

You cannot define instance fields in interfaces (they are constant - static final - values, thanks to Jon, since they're part of the implementation only. Thus, only the getter and setter are in the interface, whereas the field comes up in the implementation.

And setNumber should return a void instead of int. For getting I suggest you to add int getNumber().

public interface MyInterface {
  void setNumber(int num); // public is implicit in interfaces
  int getNumber();         // obviously
}

public class MyClass implements MyInterface {
  private int number = 0;

  public void setNumber(int num) { this.number = num; }
  public int getNumber() { return this.number; }
}

As you can see, only setNumber is part of MyInterface. Consumers do not need to know about how the number is stored, therefore it is an implementation detail.

Besides, in Java you name classes and interfaces in PascalCase rather than camelCase.