Let's say we have a setup like this
public class foo {
int number = 0;
public void setNumber(int number) {
this.number = number;
}
}
public class bar extends foo {
/* Some other utilities added to the foo class */
public bar() {
super();
}
}
And we have this task running
Scheduler.schedule(1000/* Every second */, () -> {
fooManager.forEach(f -> System.out.println(f.getNumber()));
})
Now if we do this:
Foo fo = new foo();
fooManager.store(fo);
Bar ba = new bar();
How can I make ba
access fo
setNumber()
method on ba.setNumber()
without storing fo
in ba
and doing ba.getFoInstance().setNumber()
and do ba.setNumber()
instead
Explanation v2: I want ba.setNumber()
to call fa.setNumber()
Looking for something like this: Bar ba = fo
but you can't do that since it throws ClassCastException
.
It seems to me that what you're trying to achieve is a proxy object.
Why shouldn't you want to keep a reference to Foo
inside instances of Bar
class? It could make sense something like this:
public class Bar extends Foo {
private Foo fa;
public bar(Foo fa) {
super();
this.fa = fa;
}
@Override
public void setNumber (int number) {
fa.setNumber(number);
}
@Override
public int getNumber () {
return fa.getNumber();
}
}
You should also avoid Bar
extending Foo
, they should simply both implement the same interface that is sharing the common methods.