简体   繁体   中英

How can I implement an abstract method with parameter as Child class?

ParentClass = {
  def execute(ParentParameterClass parentParamaterClass);
}

ChildClass implements ParentClass = {

 @override
 def execute(ChildParameterClass childParameterClass) = {
     print("Hurray")
 }
}


ChildParameterClass childParameterClass = new ChildParameterClass()
ParentClass parentClass = new ChildClass()
parentClass.execute(childParameterClass) // prints "Hurray"

FYI: ChildParameterClass is the child of ParentParameterClass

I know this will fail since override will throw an error.

In future there can be new child classes (like ChildClass), so I want this to be extensible, so having multiple execute method in ParentClass won't work.

Is there someway I can achieve this? I don't want to use the ParentParameterClass in ChildClass since I want to force the user to pass the ChildParameterClass when using with ChildClass.

I want to do this in Java and Python

Thanks

If the parameter objects you are trying to pass are as you state, you just need to change this to:

...
 @override
     def execute(ParentParameterClass childParameterClass) = {
         print("Hurray")
     }
}
ParentParameterClass childParameterClass = new ChildParameterClass()

and have ChildParameterClass inherit ParentParameterClass.

The other option is to use generics to allow you to pass different types to the method.

However, I'd advise against abusing inheritance by forcing override methods to accept totally different parameters as this is likely to cause maintenance issues. If the parameters are really quite different create a new method for the child instead.

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