Reputation: 537
Is there a compiler meta for Class declaration, that prevents creating Class instance before extending it? In other words - some sort of opposite of @:final
meta.
Like so (last line of code):
class A {
// ...
}
class B extends A {
// ...
}
// ...
var b = new B(); // OK
var a = new A(); // induce compiler-error
Upvotes: 3
Views: 254
Reputation: 19026
Both the other answers are correct (no constructor or private constructor), but there are a few more details that you may interest you:
A
simply doesn't have a constructor, and B
simply doesn't call super()
. Other than that, everything else works as you'd expect.new A()
, but you do still need to call super()
from B
's constructor.Technicalities:
A
to get an implicit constructor, automatically. Don't worry, this doesn't affect constructability or whether you need to call super()
. But know that it is there, and if necessary an implicit super()
call is prepended to B
's constructor. See the JS output to verify this.A
at runtime with var a = Type.createInstance(A,[]);
as compile-time type checks do not limit RTTI.Related discussion:
Aside from private/no constructor, Haxe doesn't have a formal notion of abstract classes1 (base classes not expected to be instantiated) or abstract methods2 (functions on abstract base classes with no implementation that must be implemented by a derived class.) However, Andy Li wrote a macro for enforcing some of those concepts if you use them. Such a macro can detect violations of these rules and throw compile-time errors.
1. Not to be confused with Haxe abstracts types, which are an entirely different topic.
2. Not to be confused with virtual functions, which wikipedia describes as a function which can be overridden (though various docs for various languages describe this highly loaded term differently.)
Upvotes: 2
Reputation: 537
One way of achieving this is to create private Class constructor:
class A {
private function new() {
// ...
}
}
// ...
var a = new A(); // Error: Cannot access private constructor
Upvotes: 1