Search code examples
javainheritancearraylistdynamic-binding

How come dynamic binding doesnt apply here?


I made several classes. GeoUnit is the baseclass from which County and Holding are directly extended. County however has a substructure consisting of Holdings.

When I use the toString() method of county it should display its substructure ,consisting of holdings, by calling the holdings' toString() method. The problem lies in that I am puzzled that when I call the County's toString() method I get their regular name like "Wessex" ,while the Holding's toString() method only returns the hashcode instead of London for example. Isn't dynamic binding applicable in the for-each loop in the toString() method of County?

EDIT 1: Wessex and London are something small that serve as an illustration.

GeoUnit:

public class GeoUnit {

private String name;
private Color RGB;
private Image COA;

public GeoUnit(String name, Color RGB, Image COA) {
    this.name = name;
    this.RGB = RGB;
    this.COA = COA;
}

public void setName(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

County:

public class County extends GeoUnit {

private int positionLandedTitles;
private GeoUnit superstruct;
private ArrayList<GeoUnit> substruct;
private String capital;

public County(int positionLandedTitles, String name, Color RGB, Image COA, ArrayList<? extends GeoUnit> substruct, String capital, GeoUnit superstruct) {
    super(name, RGB, COA);
    this.positionLandedTitles = positionLandedTitles;
    this.substruct = substruct;
    this.capital = capital;
    this.superstruct = superstruct;
}

@Override
public void setName(String name) {
    super.setName(name);
}

@Override
public String toString() {
    String a = "";
    for (GeoUnit g : substruct) {
        a += g.toString() + "\n";
    }
    return ("Name County: " + super.getName()+ "\n \t\t\tSubstruct: " + a);
}

Holding:

public class Holding extends GeoUnit {

public Holding(String name, Color RGB, Image COA) {
    super(name, RGB, COA);
    this.name=name;
}

@Override
public void setName(String name) {
    super.setName(name);
}

@Override
public String getName(){
    return super.getName();
}

Solution

  • You should define the toString() method in the Holding class. As it is not defined there, nor in the super class (GeoUnit), then the super-super class method is used (Object)