Why abstract method cannot have an implementation inside the body? [closed] - oop

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am having a problem that i have to implement the parent method and the method has to be overriden in the child class for further implementation.
Why this happen? and Why the language like Java, Typescript, C# do not allow this?
Since many of you ask why do i need it.
I have a parent class called Component written in typescript
class Component {
root : HTMLElement;
constructor(root : HTMLElement) {
this.root = root;
this.decorate();
}
abstract decorate();
}
class Field extends Component {
this.id;
constructor(root : HTMLElement) {
super(root);
}
decorate() {
this.id = this.root.getAttribute(data-id);
}
}
class InputField extends Field {
inputField : HTMLElement;
constructor(root : HTMLElement) {
super(root)
}
//i want to force users to override this
decorate(){
//and to call this
super.decorate();
this.inputField = this.root.getElementById('input-field');
}
}

Because abstract method purpose is to have its definition in super class and force child classes to override and implement it.
From Java Doc:
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
If you want to have an implementation in the abstract method you should not declare method as abstract and remember to override it in child classes calling super method if needed.

Related

kotlin: how to use KProperty2? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I understand that KProperty1 represents a property on a class, such as MyClass::myProperty.
I'm having trouble understand how KProperty2 should be used, or even what the concrete use case is for that pattern?
Thanks
It's as documentation states for properties that take two receivers like extension property declared in a class.
Do note that calling extension functions and properties declared within class has be done within that class itself or through scoping functions (as done in sample below with run {}):
Example:
data class Foo(val tag : String) {
val Int.echo
get() = "Im extension on $this within ${this#Foo}"
}
fun propTest(){
val foo = Foo("Baz")
foo.run {
println(5.echo) // prints Im extension on 5 within Foo(tag=Baz)
}
val tagRef : KProperty1<Foo, String> = Foo::tag
val echoRef : KProperty2<Foo, Int, String> = Foo::class.declaredMemberExtensionProperties.first() as KProperty2<Foo, Int, String>
println(echoRef.get(foo, 7)) // prints Im extension on 7 within Foo(tag=Baz)
}
I don't know if it's possible to directly reference those extensions (Int::echo within class scope just causes error) that's why I used declaredMemberExtensionProperties (which is actually a List<Kproperty2<Foo, *, *>>) to fetch it.

When defining the behavior of an object, is it better to pass an anonymous object or a callback? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Let's say we have a class that performs some action on its own and receives the result.
// This class cannot be modified.
abstract class BaseWorker {
fun someWork() {
// blabla...
onComplete()
}
abstract fun onComplete()
}
I know there are two ways to freely override the behavior of onComplete in the above class.
// case1
fun main() {
object : BaseWorker() {
override fun onComplete() {
// blabla..
}
}.someWork()
}
// case 2
class Worker(val callback:()->Unit): BaseWorker {
final override fun onComplete() {
callback()
}
}
fun main() {
Worker(callback= { //blabla... }).someWork()
}
Either one works fine, but I'm not sure which of these two behaviors should be the way to go in Kotlin.
Can you provide an existing document or answer directly on this?
Both mentioned ways are correct and would work fine. So first thing you need to take into account - your team approach. It is better to use same way in all same situations.
Then there are some factors that should be mentioned:
If responsibility on what should happen is on the class outside the worker (in your case it seems to be the root class with main method), using callback is more handy. In this way it's easier to invoke various code on work completion.
If all the variability should be encapsulated in BaseWorker children, it's totally should be as implementation of an abstract method.

Kotlin Generic function type return child class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to create a class where generic operations can be performed on classes that has inherited from it. I have tried using sealed classes, inline functions to no success, hopefully someone can provide some insight on this.
Example
class Base {
fun add // does the operation
}
data class A(val a: Int, val b: Int) : Base
data class B(val c: Int, val d: Int) : Base
val example = A(1,2)
example.add(A(3,4))
println(example)
// A(4,6)
val example2 = B(5,6)
example2.add(B(7,8))
println(example2)
// B(12, 14)
What you're looking for is self-referential generics.
abstract class Base<B : Base<B>> {
abstract fun add(other: B): B
}
data class A(...) : Base<A>
data class B(...) : Base<B>

How to instantiate an object that implements a java interface? (that is, 2 lambdas) [duplicate]

This question already has answers here:
How to create an instance of anonymous interface in Kotlin?
(5 answers)
Closed 2 years ago.
I have this Java interface:
public interface MetronomeCallback {
void onTick(boolean tickValue);
void onBPM(int bpm);
}
public void setMetronomeCallback(MetronomeCallback metronomeCallback) {
this.metronomeCallback = metronomeCallback;
}
This is a lambda function in java, I'm supposed to pass an object to setMetronomeCallback that implements these 2.
I want to implement it inline, like this:
val metronomeCallback = MainService.MetronomeCallback {
fun onTick(value: Boolean) {
}
fun onBPM(bpm: Int) {
}
}
s.setMetronomeCallback(metronomeCallback);
How to create an object that implement these 2 functions?
It's obvious when you know: to create an object that implements some interface, you use object : Interface { … }.
So in this case, I think you just need to insert object : before the interface name.
(You can extend a class similarly; you just need to add parens and any constructor parameters after the classname.  And you can inherit from multiple interfaces/classes, by separating them with a comma.)
The technical term for this is an object expression; it's all explained in the language docs.

Best practice for enforcing type safety in polymorphic inheritance hierarchies [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I seem to run into this situation quite a lot and have yet to find a solution that I find acceptable.
Quite often I will have parallel inheritance hierarchies where a method in one hierarchy gets passed the matching class from the other hierarchy as a parameter.
Here is an example that probably explains this better.
abstract class Animal
{
public virtual void Eat(Food f)
{
}
}
abstract class Food
{
}
class LionFood : Food
{
}
class ElephantFood : Food
{
}
class Lion : Animal
{
public override void Eat(Food f)
{
// It is only ever valid to pass LionFood here as the parameter.
// passing any other type of Food is invalid and should be prevented
// or at least throw an exception if it does happen.
}
}
In the past, I have usually made the base class generic to allow the implementing concrete class to define the type as follows..
abstract class Animal<T> where T : Food
{
public abstract void Eat(T f);
}
class Lion : Animal<LionFood>
{
public override void Eat(LionFood f)
{
}
}
At first this seems like a very good solution because it provides compile-time type safety. But the more I use it, the more I am starting to think that using generics in this way is infact an anti-pattern. The problem is that the Animal base class cannot be used in a polymorphic way. You cannot, for example, easily write a method that will process any type of Animal regardless of its actual concrete type.
Every time I use this generics solution, I always seem to end up with covariant and contravariant interfaces all over the place just to try and provide the polymorphic behaviour I want. This gets out of hand pretty quickly and some functionality is not possible simply because the correct interface cannot be provided.
Of course another option is to not use generics and perform runtime type checking in the Eat method like this:
public override void Eat(Food f)
{
if (f.GetType() != typeof(LionFood))
{
throw new Exception();
}
}
This is better than nothing I suppose but I'm not a huge fan of it simply because of the lack of compile-time type safety.
So after all that.. My question is.. What is the best practice to provide polymorphic behaviour while at the same time ensuring some type safety?
Is there some OO design trick or pattern that I am missing that will allow me to avoid the parallel inheritance hierarchies all together?
I appreciate that this question is somewhat subjective, but there are points available for everyone who contributes and I'll choose the best response as the answer.
Thanks for looking.
Edit:
Having thought about this I realise that my example given doesn't really make sense. Of course it is not possible to use Animal in a polymorphic way because the type passed to Eat will always depend on the actual underlying type of Animal (which the initiator of a polymorphic call will not know)! I need to think of a better example that illustrates my actual situation.
I think common sense and the requirements of the domain will dictate the proper approach. Working with this example, I'd do like this
public class Lion:Animal
{
public override void Eat(Food f)
{
Eat(f as LionFood);
}
public void Eat(LionFood food)
{
//check for null food
//actually consume it
}
}
Edit
I think using generics is not suited in this case, because what if an Animal can play with a Toy, hunt a specific Animal and so on. You can have a number of methods with arugments that implement an abstraction, it's awkward to use generics every time there is a method with an argument that uses polymorhpism.
Ok, could that be what you want? Sometimes, when you can't articulate what you want to do, what you want is actually a mixin.
template<typename base>
class Eater: public base {
template<typename T>
Eat(T (extends Food) food) { // you can do that extends thing in C++ but I won't bother
// register what's eaten, or do whatever
base::Eat(food);
}
}
class Lion {
Eat(LionFood food) {
cout<<"Hmm delicious!";
}
}
int main() {
Eater<Lion> lion;
lion.eat(LionFood());
return 0;
}
This'll give you a nice compiler error if you try to feed grass to the lion.