There are no configuration methods in the interface

I have a concrete class A that implements interface B.

B ref = new A(); 

The code:

 public interface B{ public abstract String[] getWords(); } public class A implements B { private String[] words = new String[] {}; public void setWords(String[] words){ this.words = words; } public String[] getWords(){ return this.words; } } 

In interface B, I only have a getter method, but no setter method, although class A has it.

So, when I do this: B ref = new A(); Will this code work and how do I set the words?

+6
source share
5 answers

You should revert back to the original type if the interface really shows it

 if (ref instanceof A) ((A) ref).setWords(words); else // something else. 

The best solution is to add a method to the interface.

+4
source

You cannot call setWords in ref if it is defined as B ref = ...

This is one of those cases where you need to use the exact type when declaring a variable (or use a cast):

 A ref = new A(); 

As an alternative:

  • you can create a C interface that extends B and contains both methods and has an implementation of A.
  • you can provide a constructor in A that takes a String[] words argument to initialize your words field, and not provide a setter at all.

I would personally approve the last option:

 public class A implements B { private final String[] words; public A(String[] words) { this.words = words; } public String[] getWords() { return this.words; } } 
+5
source

So, when I do this: B ref = new A () ;, this code will work ...

Yes it will.

... and how will I set the words?

You cannot, unless you:

  • make A constructor to take a list of words; or
  • add setWords() to B ; or
  • keep a reference to type A to your object; or
  • downcast ref to A

Of these, I would go with one of the options 1-3. The latter option is included for completeness only.

+5
source
 B ref = new A();//1 ref.setWords(whatever);//2 

The above code will not compile, since setWords() not defined in your interface B , you will get a compiler error in line 2.

as others have already expressed their answers. you have 2 options to work around

  • Create an object as A ref = A ();
  • Drag ref to type A, for example ((A) ref) .setWords (watever);
+3
source

So, when I do this: B ref = new A () ;, this code will work

Yes

and how to set words?

You can not. You need to have a configuration method in your interface.

Meanwhile, you do not need to define the method as abstract. This is abstract by default.

0
source

All Articles