class extending combining with references
Hi ya'll!
Suppose I have the following classes:
Code:
public class A extends B{
C c1;
public A(){
c1 = new C();
somethingB();
}
}
Code:
public class B {
public B(){
}
public void somethingB(){
c1.anythingC();
}
}
How can I access the object c1 from the class B? Do I have to pass a reference this way?
and
Code:
public void somethingB(C c1){
c1.anythingC();
}
Or are there other solutions? Thanks for replying!
Re: class extending combining with references
This seems terribly disjointed and terribly wrong. The base class should have no knowledge at all about any child class and certainly should have no dependencies on a child class. You need to rethink your design completely. One possible solution is to use a dependency injection though.
I'm no pro at this, but something like this:
Code:
class Parent {
public void doSomething(Injectable myInjection) {
myInjection.myMethod();
}
}
Code:
class Child extends Parent {
Injectable myInjectable;
public Child() {
myInjectable = new Injectable() {
public void myMethod() {
System.out.println("inside of my method");
}
};
doSomething(myInjectable);
}
}
Code:
interface Injectable {
void myMethod();
}
Re: class extending combining with references
Though even that looks skunky, especially a class calling a virtual method inside of a constructor like that. More often you'd see something like this:
Code:
public class Foo {
public static void main(String[] args) {
Injectable inject = new Injectable() {
public void myMethod() {
System.out.println("in myMethod");
}
};
Parent parent = new Parent(inject);
parent.doSomething();
}
}
class Parent {
Injectable myInjectable;
Parent(Injectable myInjectable) {
this.myInjectable = myInjectable;
}
public void doSomething() {
myInjectable.myMethod();
}
}