• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 279
  • Last Modified:

Interface of constant values question

I am trying to get the following to compile.  I am not sure how the syntax works when using an interface that only contains constant values.

The "play" method of both base class "InstrumentX" and derived class "WindX" use the constants in interface NoteX, however, since NoteX resolves to a constant int I get the following error.  

How do I remedy the situation?
----------------------------------ERROR-------------------------------------
C:\java\code\c08>javac WindError.java
WindError.java:20: play(NoteX) in InstrumentX cannot be applied to (int)
    i.play(NoteX.MIDDLE_C);
-----------------------------------CODE--------------------------------------
//: WindError.java
 interface NoteX {
        public static final int
                MIDDLE_C = 0, C_SHARP = 1, C_FLAT = 2;
      }
class InstrumentX implements NoteX {
  public void play(NoteX n ) {
    System.out.println("InstrumentX.play()");
  }
}
class WindX extends InstrumentX {
    public void play(NoteX n ) {
    System.out.println("WindX.play(NoteX n )");
  }
}
public class WindError {
  public static void tune(InstrumentX i) {
    i.play(NoteX.MIDDLE_C);
  }
  public static void main(String[] args) {
    WindX flute = new WindX();
    tune(flute);   }
} ///:~
0
kellyputty
Asked:
kellyputty
  • 3
1 Solution
 
Tommy BraasCommented:
When you specify that a method accepts a parameter of type NoteX, you have to ensure that you pass a class instance which does just that.
0
 
Tommy BraasCommented:
In this case you're trying to pass an int. Even though that int is defined in your interface, the int itself can never be a NoteX.

Change your interface to an abstract class, and let the InstrumentX extend it.

Like:

 abstract class NoteX {
   private int note;
   private NoteX(int note) {
      this.note = note;
   }
   
   public static final NoteX MIDDLE_C = new NoteX(0);
   public static final NoteX C_SHARP = new NoteX(1);
   public static final NoteX C_FLAT = new NoteX(2);
}
0
 
Tommy BraasCommented:
;-D
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now