Wednesday, 2 October 2013

Java: I can't override toString() properly to print an arraylist when there's different classes involved

Java: I can't override toString() properly to print an arraylist when
there's different classes involved

This is hard to describe well but I'll do the best I can. I have an
arraylist of objects. Inside those objects are attributes. Instead of
everything inside one class, they are all separate classes. This is the
first time I'm working with stuff like this and I'm not sure if I got the
syntax right. I'm trying to make println print out the stuff inside the
arraylist and not bytecode.
//main.java
public class Main {
public static void main(String[] args) {
world w = new world();
}
}
//world.java
public class world {
ArrayList<object> list = new ArrayList<>;
public void makeObjectA{
list.add(new ObjectA())
}
public void makeObjectB{
list.add(new ObjectB())
}
@Override public String toString () {
ObjectA obja = new ObjectA();
ObjectB objb = new ObjectB();
return "A: " + obja.getattra() + ", B: " + objb.getattrb();
}
System.out.println(list);
}
//ObjectA.java
public class ObjectA extends world {
private int attra = 10;
public int getattra() {
return attra;
}
public void setattra(int attra) {
this.attra = attra;
}
}
//ObjectB.java
public class ObjectB extends world {
private String attrab = "Ten";
public String getattrb() {
return attrb;
}
public void setattrb(String attrb) {
this.attrb = attrb;
}
}
The output prints out bytecode. I'm not sure what I'm doing wrong
(probably the syntax everywhere). Help please?

No comments:

Post a Comment