Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No setter methods in interface

I've a concrete class A that implements an interface B.

B ref = new A();

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 the interface B, I've only getter method but no setter method though the class A has it.

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

like image 615
Mercenary Avatar asked Dec 19 '12 10:12

Mercenary


People also ask

What is an interface with no methods called?

A marker interface is an interface that doesn't have any methods or constants inside it. It provides run-time type information about objects, so the compiler and JVM have additional information about the object. A marker interface is also called a tagging interface.

Can an interface have getters and setters?

You cannot define instance fields in interfaces (unless 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.

Why are there no getters and setters?

Getter and setter methods (also known as accessors) are dangerous for the same reason that public fields are dangerous: They provide external access to implementation details. What if you need to change the accessed field's type? You also have to change the accessor's return type.

Can we use getter without setter?

All of these methods are referred to as getters and setters, even when a backing variable is used. It is not possible to access any controller variables without a getter or setter.


1 Answers

You won't be able to call setWords on ref if it is defined as B ref = ....

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

A ref = new A();

Alternatively:

  • you could create an interface C that extends B and contains both methods and have A implement C.
  • you could provide a constructor in A that takes a String[] words argument to initialise your words field, and not provide a setter at all.

I would personally favour the latter option:

public class A implements B {

    private final String[] words;

    public A(String[] words) {
        this.words = words;
    }

    public String[] getWords() {
        return this.words;
    }
}
like image 67
assylias Avatar answered Nov 09 '22 23:11

assylias