Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic getter and setter methods [closed]

I am trying to write an abstract class. This class is going to be a Field. There will be different types of fields which will need to extend the field class and write its own setter class. For example....There will be a String Field and an Integer Field.

String Field will need to extend the Field class but must have it's own setValue and getValue method which has a String variable to set and return. Number Field must do the same with Integer.

I think the best way is to have a Generic Type set Value in the super class but I am not sure how to do about this. Any help much appreciated.

like image 498
user3859651 Avatar asked Oct 12 '25 18:10

user3859651


2 Answers

You can make your super class generic:

public abstract class Field<T>{
  private T value;

  public void setValue(T value){
     this.value = value;
  }

  public T getValue(){
     return value;
  }
}

if you now extend it like:

public class StringField extends Field<String>{
   //nothing to do here.
}

you are already done.

like image 171
dognose Avatar answered Oct 14 '25 09:10

dognose


Like this:

public abstract class Field<T> {
    private T value;
    // + constructor(s)
    public T get() {
        return value;
    }
    public void set(T value) {
        this.value = value;
    }
}

public class StringField extends Field<String>{}
public class IntField extends Field<Integer>{}

You might want to add constructors such as Field(T value) and StringField(String s).

like image 40
Jean Logeart Avatar answered Oct 14 '25 09:10

Jean Logeart