Is there a way in Haxe to get the equivalent of Java's abstract methods and abstract classes?
What I want is
// An abstract class. (Written in a Java/Haxe hybrid.)
abstract class Process<A> {
public function then<B>( f : A -> Process<B> ) : Process<B> {
var a : A = go() ;
return f(a) ;
}
abstract public function go( ) : A ;
}
// A concrete class.
class UnitP<A> extends Process<A> {
var _a : A ;
public function new( a : A ) {
_a = a ; }
public override function go() : A { return _a ; }
}
The closest I've been able to get is to define Process
as an interface and to implement it with a conceptually abstract class ProcessA
, which defines both methods; the implementation of go
in ProcessA
simply crashes. Then I can extend my conceptually concrete classes off ProcessA.
A method declared using the abstract keyword within an abstract class and does not have a definition (implementation) is called an abstract method. When we need just the method declaration in a super class, it can be achieved by declaring the methods as abstracts.
No. Abstract class can have both an abstract as well as concrete methods. A concrete class can only have concrete methods. Even a single abstract method makes the class abstract.
A class containing abstract methods should also be abstract. We cannot create objects of an abstract class. To implement features of an abstract class, we inherit subclasses from it and create objects of the subclass. A subclass must override all abstract methods of an abstract class.
To declare an abstract method, use this general form: abstract type method-name(parameter-list); As you can see, no method body is present. Any concrete class(i.e. class without abstract keyword) that extends an abstract class must override all the abstract methods of the class.
As mentioned by MSGhero, Java-style abstracts are not natively supported by Haxe. It was requested by several people though, so Andy Li wrote a macro to provide Haxe users with a comparable functionality:
https://gist.github.com/andyli/5011520
How I'd do something equivalent in Haxe
Create a class that inherits from the Abstract and implements the Interface.
// An interface
interface IProcess<A, B> {
public function then( f : A -> AProcess<B> ) : AProcess<B>;
public function go() : A;
}
// An abstract class.
class AProcess<A, B> {
private function new() {}
public function then<B>( f : A -> AProcess<B> ) : AProcess<B> {
var a : A = go() ;
return f(a) ;
}
private function go() : A {};
}
// A concrete class.
class UnitP extends AProcess<A, B> implements IProcess {
var _a : A ;
public function new( a : A ) {
super();
_a = a ;
}
public function go() : A { return _a ; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With