我怎样才能打印Object的内容,而不是它的地址

时间:2015-10-02 07:12:43

标签: object printing types

我在Code中遇到问题,我想打印对象的内容,例如,在我想打印的类(rect)中(x和y,id .....) 知道我已经将它作为超类类型的对象存储在链表中, 看看我的课程:

public class rec extends Shape {

    int x , id ;
    double y ;
    String style ;
    int width , height ;

    public rec (  int xs  , double ys , int id , String st ) {
        x = xs ;
        y = ys ;
        style = st ;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public double getY() {
        return y;
    }

    public void setY(double y) {
        this.y = y;
    }

    public String getStyle() {
        return style;
    }

    public void setStyle(String style) {
        this.style = style;
    }


}

和马戏团一样:

public class circ extends Shape { 

    int cx , cy , r , id ;
    String Style ;

    public circ ( int i , int cx1 , int cy1 , int re , String st ) {
        id = i;
        cx  = cx1;
        cy = cy1 ;
        r = re ;
        Style = st ;
    }

    public int getCx() {
        return cx;
    }

    public void setCx(int cx) {
        this.cx = cx;
    }

    public int getCy() {
        return cy;
    }

    public void setCy(int cy) {
        this.cy = cy;
    }

    public int getR() {
        return r;
    }

    public void setR(int r) {
        this.r = r;
    }

    public String getStyle() {
        return Style;
    }

    public void setStyle(String style) {
        Style = style;
    }



}

最后,超级班:

public class Shape {

    final int width = 800;
    final int higth = 600 ;
    public int getWidth() {
        return width;
    }
    public int getHigth() {
        return higth;
    }


}

主要:

rec re = new rec(9 , 94.4 , 5 , "F");
    circ c = new circ(4 , 5 , 3 , 9 , "E");

    LinkedList<Shape> r = new LinkedList<Shape>();
    r.insert(re);
    r.insert(c);
    r.print(r);

打印方法是:

public static<T> void print(LinkedList<T> l) {
    if (!l.empty()) {
            l.findFirst();
            while (!l.last()) {
                    System.out.println(l.retrieve());
                    l.findNext();
            }
            System.out.println(l.retrieve());
    }

}

我有这个输出:

rec@2a139a55
circ@15db9742

任何帮助?

1 个答案:

答案 0 :(得分:0)

也许只是覆盖你的类的toString()方法就足够了

 public String toString() {
   return "rect ==> x:"+x+", y:"+y;
 }