简体   繁体   中英

Calling extended's class method from parent class with extended class keeping instances of parent's variables

I'm implementing a visitor pattern for a particular domain, where I have some BaseVisitor , ie:

public class BaseVisitor {
    someC someInstance;

    visitA(...) {
        ...
    }

    visitB(...) {
        ...
    }
}

and a class that changes one particular functionality, ExtendedVisitor , ie:

public class ExtendedVisitor extends BaseVisitor {    
    visitA(...) {
        ...
    }
}

This ExtendedVisitor has a different implementation of visitA .

What I want to do is that when I'm in visitB of BaseVisitor , in special case I want to use the method of the ExtendedVisitor ( visitA ) as opposed to the regular visitA of the BaseVisitor itself. This works fine, ie.:

visitB(...) {
    if (...)
        new ExtendedVisitor().visitA();
    else
        visitA();
}

Now obviously, in the BaseVisitor there are many visit methods, and so the visitA of ExtendedVisitor will call them (ie. the original implementation of those methods - in BaseVisitor ). The problem is that at this point I lost the instance of someInstance (ie. it is null ). Is there a way for the two classes to share the variables? Ie. let the child use parent's variables?

Since you are calling to new ExtendedVisitor() you are creating a new instance of that class and of course someInstance will be null. You could create a constructor like

public ExtendedVisitor(someC someInstance ){
   this.someInstance = someInstance
} 

But it doesn't sound a great idea...

With your design you are forcing your parent class to know the functionality of its children classes. I see a coupling issue here. Probably you should rethink your code and use inheritance and polimorfism in a better way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM