I'm trying to get objects from user1 when toString() is run from within user2 but when I use super it refers to Object instead of user1. I think I may have to use reflection but I'm not sure. How can I get super.objects.get(0) for user1 when in its child, user2?
public abstract class Foo {
public List<Object> objects = new ArrayList<>();
public void add(String string) {
objects.add(string);
}
@Override
public String toString() {
//This line is broken:
Object object = super.objects.get(0);
}
}
>
public class User extends Foo {}
>
public static void main(String args[]) {
User user1 = new User();
User user2 = new User();
user1.add(user2);
user2.toString();
}
If your objects field is public (bad practice!), protected or package-protected (no explicit access modifier), your child classes will be able to access it directly (if within the same package for the last case).
A super invocation from Foo will return an instance of Object because Foo doesn't explicitly extend any class, hence it extends Object.
You only need to implement your toString() override as return String.valueOf(objects) or String.valueOf(objects.get(myIndex)) - check for empty/null in the second case.
The method will be dynamically resolved at runtime and can be invoked from User instances, thus representing objects or whichever object indexed.
Here's a simple self-contained example, that prints out the whole collection:
public class Main {
public static void main(String[] args) {
System.out.println(new Bar());
}
static class Foo {
// package-protected field. A Bar instance will have access here.
List<Object> objects;
@Override
public String toString() {
// printing representation of "objects" and avoiding NPE
return String.valueOf(objects);
}
}
static class Bar extends Foo {
// overriding default constructor and initializing/populating "objects"
Bar() {
objects = new ArrayList<Object>();
objects.add(1);
}
}
}
This will print out [1].
Side-note
Also, a method returning String should actually return String.
Which your toString override does not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With