Home > Mobile >  In Java, can I have a parent class implement a method that uses a variable from a subclass?
In Java, can I have a parent class implement a method that uses a variable from a subclass?

Time:10-29

I'm looking to simplify some methods that are shared across all of my subclasses, in which case there's 25 . I currently use an interface to implement

public int getRow() {
    return row;
}
public boolean getCondition() {
    return condition;
}

and a few more that are similar in nature (getters/setters)

Is it possible to define a method in the parent class body that uses the subclass variable and avoid having these generic getters and setters in the subclass?

CodePudding user response:

This is not possible, for obvious reasons: There is no guarantee that every subclass actually has that variable, therefore it is not possible to refer to it short of reaching for obviously silly ideas such as reflection.

However, if you feel that every subclass of this class really would have these 2 fields, then, shouldn't those fields just be part of the parent class instead? If you have:

public abstract class SpreadsheetRowMarker {}

public final class InvoiceRowMarker extends SpreadsheetRowMarker {
  private final int row;

  public InvoiceRowMarker(int row) {
    this.row = row;
  }

  public int getRow() {
    return row;
  }
}

// another 24 classes a lot like InvoiceRowMarker

and not just that, but it is effectively ingrained in the very nature of whatever SpreadsheetRowMarker is attempting to represent that ALL imaginable subclasses of it would look like that, then the above seems weird. If it's functionality that is intrinsically bundled up with SpreadsheetRowMarker itself, just make it part of that:

public abstract class SpreadsheetRowMarker {
  private final int row;

  public SpreadsheetRowMarker(int row) {
    this.row = row;
  }

  public int getRow() {
    return row;
  }
}

public final class InvoiceRowMarker extends SpreadsheetRowMarker {
  public InvoiceRowMarker(int row) {
    super(row);
  }
}

// and 24 more such classes

unfortunately you can't get rid of those constructors, but presumably you already had 24 constructors that took in a row variable. The above means getRow() is now centrally placed, and that you can now invoke it on anything as long as you know it is a SpreadsheetRowMarker (vs knowing it's any one of its many subclasses).

If you have 25 types that all extend SpreadsheetRowMarker but you CAN imagine subtypes that don't have it, then consider making another class to 'sit in between' (if you have class F extends A {} right now, make a new abstract class B extends A {} and then have your 25 current classes with getRow extend B instead. Put the getRow stuff in B.

  • Related