samedi 22 juillet 2017

java getSuperclass().toString() not running my custom toString() (reflection)

[Hi, guys. I'm learning Java with Cay Horstmann's 'Java SE8 for the Really Impatient'. Studying chapter 4]

I want to call the toString() method of the parent class and add something to it. Unfortunately, the call to the toString() method of the parent class seems not to be working.

So far I've got these classes:

public class Point {
    private double _x = 0;
    private double _y = 0;

    public Point(double x, double y) {
        _x=x;
        _y=y;
    }

    @Override
    public String toString() {

        String theString = getClass().getSuperclass().toString() + " => " + getClass().getCanonicalName();

        theString += "[";
        int i=0;
        for (Field theField : getClass().getDeclaredFields()) {
            theField.setAccessible(true);
            try {
                if (i>0) theString += ", ";
                theString += theField.getName() + ": " + theField.get(this).toString();
                i++;
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(Point.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("err1");
            } catch (IllegalAccessException ex) {
                Logger.getLogger(Point.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("err2");
            }
        }
        theString += "]";
        return theString;
    }
    ...        
}

public class LabeledPoint extends Point {
    private String _label = "";

    public LabeledPoint(String label, double x, double y) {
        super(x, y);
        this._label = label;
    }

    ...

}

And I call them with this main method:

public static void main (String[] args) {
    LabeledPoint lp1 = new LabeledPoint("FirstPoint", 10.5, 30);
    System.out.println("The new point is:");
    System.out.println(lp1);
}

So, I was expecting to get something like this:

Point[_x: 10.5, _y:30.0]=>LabeledPoint[_label: FirstPoint]

But instead, I'm getting :

Point=>LabeledPoint[_label: FirstPoint]

That is, the getClass().getSuperclass().toString() is not executing Point.toString(), but it's just printing out the canonical name.

Why is that?





Aucun commentaire:

Enregistrer un commentaire