简体   繁体   中英

Understanding Java Inheritance and function creation

I have a base class which goes as below

class BaseClass{
  //this is a base class
  // I dont want to add any generic methods here as it is 
  //extended by tens of classes
}

Now Two particular classes which extends this base class

class Abc extends BaseClass{

//method
  void letsGo(){
    //this method is not there in base class
  }
}
class Xyz extends BaseClass{

//method
void letsGo(){
    //this method is not there in base class
  }

}

Now I need a function which have to accepts Class Xyz's object or Class Abc's object with a syntax similar to below

void run (BaseClass base){
  base.letsGo() // I know it wont work 
}

and call it like run(object of Abc) or run(object of Xyz) .

How do I implement this. I dont want to add abstract method in base class as it is extended by many classes

Your issue seems to be that the parent class BaseClass will be inherited by many children, but only a small subset of the children will need to implement letsGo . I think the easiest solution is to make an intermediate subclass, say MediumClass (extending BaseClass ) that contains the method letsGo and then make Abc and Xyz inherit that. Finally, make the run method take the intermediate class as the argument.

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