1

I have a sample interface

 public interface SampleVariables {
int var1=0;
int var2=0;
}

and I want to use var1 and var2 across multiple classes i am trying to do this using

public class InterfaceImplementor  extends Message  implements SampleVariables{

private int var3;

public int getVar1(){
    return var1;
}

public void setVar1(int var1){
    SampleVariables.var1=var1; // ** error here in eclipse which says " remove final modifier of 'var1' " Though I have not defined it as final
}

public int getVar3() {
    return var3;
}

public void setVar3(int var3) {
    this.var3 = var3;
}

}

where class Message is a pre-defined class which I try to use and I cannot define var1, var2 in the class Message.

Is there a better way to do this? Or am I missing something really simple ?

bhavs
  • 2,091
  • 8
  • 36
  • 66

4 Answers4

2

All fields in an interface are implicitly static and final, hence your warning above. See this SO question for more details.

It seems to me that you want a base class with these variables, but as you've noted you can't do this since you're deriving from a 3rd party class.

I would not derive from that 3rd-party class, since you don't control its implementation. I would rather create a class that wraps it and provides your additional functionality. That gives you a level of comfort that if/when that 3rd-party class changes, you can limit the scope of the changes that you have to subsequently make.

Unfortunately Java doesn't support mixins, which is what you're trying to achieve here.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

In interface by default variables are static final you cannot change there value ie. you cannot do SampleVariables.var1=var1;

what you can do is

public class InterfaceImplementor  extends Message { // do not implement interface here

private int var3;
private int var1;

public void setVar1(int var1){
    this.var1=var1; // will work
}

and to access variable of interface SampleVariables.var1

Harmeet Singh
  • 2,555
  • 18
  • 21
1

Since member variable of Interface are by default static, final so you can't reassign the value again once you have initialized.

Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

See Java Language Specification.

amicngh
  • 7,831
  • 3
  • 35
  • 54
0

You should use an abstract class for this.

example:

public abstract class AbstractClass {
    protected int var1;
}
class SubClass1 extends AbstractClass {

}
class SubClass2 extends AbstractClass {

}

This way SubClass1 and SubClass2 will have a var1. Note that you can do the same with getters and setters, but for making the point this was shorter.

Tom
  • 4,096
  • 2
  • 24
  • 38