Mark Haxe Class for forced extend? - class

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

Simply don't declare a constructor at all for class A

Both the other answers are correct (no constructor or private constructor), but there are a few more details that you may interest you:
Here's an example of no constructor. Of note is that A simply doesn't have a constructor, and B simply doesn't call super(). Other than that, everything else works as you'd expect.
Here's an example of a private constructor. You still can't instantiate a new A(), but you do still need to call super() from B's constructor.
Technicalities:
Use of some features (like a default value on a member variable) will cause 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.
In any case, know that you can still instantiate an 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.)

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

Related

Why should we use the 'override' key word in Kotlin for abstact class members?

If the base class has an abstract method or property, than these members must be overriden in the child class. The documentation says that i must use key word 'override' every time for such members, because i must implement methods or initialize properties in the child class. For example:
abstract class Dwelling {
abstract val buildingMaterial: String
abstract fun hasRoom() : Boolean
}
class RoundHut : Dwelling() {
override val buildingMaterial = "Stone"
override fun hasRoom() : Boolean {
return true
}
}
If an abstract method and a property must be overriden and implemented in child class any way (and compiler know this), than why we should write 'override' key word every time?
When you find yourself reading and understanding the implementing class, you have the explicit information that you're currently investigating an overridden one as it's explicitly marked as such. Kotlin likes to make things explicit and the documentation states
[...] we stick to making things explicit in Kotlin. So, Kotlin requires explicit modifiers for overridable members (we call them open) and for overrides
Java has an #Override annotation that is optional and not used by everyone although it has been considered a best practice (even as per Effective Java). Kotlin goes one step further by making it a compiler-enforced requirement.

Scala: importance during implementation of case class private

I understand that using something like
case class private A()
new A()#This will be a invalid call as A is private
But what I do not understand that as from an implementation perspective, what advantage does this provide while coding? Because calling A() twice will give 2 instances of the class anyways. If this syntax is not used to prevent instantiation like Java, then why would I want to not let someone instantiate my class using new?
Marking a case class constructor private is useless. As you've notices, case classes get a synthetic companion object with an apply method whose implementation is simply a call to the actual constructor.
Scala case classes have been designed to just "classes + the case modifier", meaning that everything that works on classes also works on case classes, which also include the (pointless) ability to specify access modifiers on the constructor.

how scala treat companion object?

I'm new to Scala with Java background.
In java when we want to share any field among different objects of class. we declare that field static.
class Car {
static NO_Of_TYRES = 4;
// some implementation.
public int getCarNoOftyres(){
NO_Of_TYRES; // although it's not a good practice to use static without class name
//but we can directly access static member in same class .
}
}
But in Scala we cannot declare static fields in class, we need to use object(companion object) for that.
In scala we will do like this,
class Car {
println(NO_Of_TYRES); // scala doesn't let us do that. gives error
println(Car.NO_Of_TYRES);// this is correct way.
}
object Car {
val NO_Of_TYRES: Int = 4;
}
I'm just curious, how scala treat companion objects?
what different these two key-words (class and object) makes ?
why does scala not letting us access NO_Of_TYRES directly in class?
Companion objects are singleton class instances (and definitions), just to recall singleton in java is more or less:
class Foo {
private Foo() { }
/* boilerplate to prevent cloning */
private static Foo instance = new Foo();
public static Foo getInstance() { return instance; }
public int bar() { return 5; }
}
and then to call method bar of this object:
Foo.getInstance().bar();
Scala removed all this boilerplate and lets you create equivalent thing with just
object Foo {
def bar: Int = 5
}
and to call it you only need
Foo.bar
now what's the difference between 'object' and 'companion object'? It's actually quite simple - companion object (so the object defined in the same file as a class and having the same name) has access to it's related class private fields and methods, and that's probably why scala authors decided that it should reside in the same file - so that references to private fields are in the same file as their declarations (which I think is always the case both in Java and Scala, unless using reflection magic)
I'd like to reference another answer about the same subject: What are the advantages of Scala's companion objects vs static methods?
See also Section 4.3 of Odersky's book Programming in Scala - Chapter 4 - Classes and Objects
Scala treats everything as pure objects with their instances. In this view a java static member is not part of any instance, it lives a separate and different life.
With the tricks of the keyword object and some syntactic sugar, you can achieve the same result but maintaining the stated principle: a single instance of that object is instantiated and a global access point for the instance is provided.
Scala, as you pointed out, cannot have static variables or methods, as known in Java. Instead, there are singleton objects, which are declared with the keyword object. Calling a method in this objects is like calling a static method in Java, except you are calling the method on a singleton object instead.
If this object has the same name of a class or trait, it is called the companion object of the class/trait. A companion object must be defined inside the same source file as the class/trait. A companion object differs from other objects as it has access rights to the related class/trait that other objects do not. In particular it can access methods and fields that are private in the class/trait.
Companion objects provide us with a means to associate functionality with a class without associating it with any instance of that class. They are commonly used to provide additional constructors

Why are singleton objects more object-oriented?

In Programming in Scala: A Comprehensive Step-by-Step Guide, the author said:
One way in which Scala is more
object-oriented than Java is that
classes in Scala cannot have static
members. Instead, Scala has singleton
objects.
Why is a singleton object more object-oriented? What's the good of not using static members, but singleton objects?
Trying for the "big picture"; most of this has been covered in other answers, but there doesn't seem to be a single comprehensive reply that puts it all together and joins the dots. So here goes...
Static methods on a class are not methods on an object, this means that:
Static members can't be inherited from a parent class/trait
Static members can't be used to implement an interface
The static members of a class can't be passed as an argument to some function
(and because of the above points...)
Static members can't be overridden
Static members can't be polymorphic
The whole point of objects is that they can inherit from parent objects, implement interfaces, and be passed as arguments - static members have none of these properties, so they aren't truly object-oriented, they're little more than a namespace.
Singleton objects, on the other hand, are fully-fledged members of the object community.
Another very useful property of singletons is that they can easily be changed at some later point in time to not be singletons, this is a particularly painful refactoring if you start from static methods.
Imagine you designed a program for printing addresses and represented interactions with the printer via static methods on some class, then later you want to be able to add a second printer and allow the user to chose which one they'll use... It wouldn't be a fun experience!
Singleton objects behave like classes in that they can extend/implement other types.
Can't do that in Java with just static classes -- it's pretty sugar over the Java singleton pattern with a getInstance that allows (at least) nicer namespaces/stable identifiers and hides the distinction.
Hint: it's called object-oriented programming.
Seriously.
Maybe I am missing something fundamentally important, but I don't see what the fuss is all about: objects are more object-oriented than non-objects because they are objects. Does that really need an explanation?
Note: Although it sure sounds that way, I am really not trying to sound smug here. I have looked at all the other answers and I found them terribly confusing. To me, it's kind of obvious that objects and methods are more object-oriented than namespaces and procedures (which is what static "methods" really are) by the very definition of "object-oriented".
An alternative to having singleton objects would be to make classes themselves objects, as e.g. Ruby, Python, Smalltalk, Newspeak do.
For static members, there is no object. The class really just is a namespace.
In a singleton, there is always at least one object.
In all honesty, it's splitting hairs.
It's more object oriented in the sense that given a Scala class, every method call is a method call on that object. In Java, the static methods don't interact with the object state.
In fact, given an object a of a class A with the static method m(), it's considered bad practice to call a.m(). Instead it's recommended to call A.m() (I believe Eclipse will give you a warning). Java static methods can't be overridden, they can just be hidden by another method:
class A {
public static void m() {
System.out.println("m from A");
}
}
public class B extends A {
public static void m() {
System.out.println("m from B");
}
public static void main(String[] args) {
A a = new B();
a.m();
}
}
What will a.m() print?
In Scala, you would stick the static methods in companion objects A and B and the intent would be clearer as you would refer explicitly to the companion A or B.
Adding the same example in Scala:
class A
object A {
def m() = println("m from A")
}
class B extends A
object B {
def m() = println("m from B")
def main(args: Array[String]) {
val a = new B
A.m() // cannot call a.m()
}
}
There is some difference that may be important in some scenarios. In Java you
can't override static method so if you had class with static methods you would not be able to customize and override part of its behavior. If you used singleton object, you could just plug singleton created from subclass.
It's a marketing thing, really. Consider two examples:
class foo
static const int bar = 42;
end class
class superfoo
Integer bar = ConstInteger.new(42);
end class
Now, what are the observable differences here?
in a well-behaved language, the additional storage created is the same.
Foo.bar and Superfoo.bar have exactly the same signatures, access, and so on.
Superfoo.bar may be allocated differently but that's an implementation detail
It reminds me of the religious wars 20 years ago over whether C++ or Java were "really" Object Oriented, since after all both exposed primitive types that aren't "really" objects -- so, for example you can't inherit from int but can from Integer.

Scala: invoking superclass constructor

I am experiencing a weird behavior by Scala handling of superclass constructors.
I have a really simple class defined in the following way
package server
class Content(identifier:String,content:String){
def getIdentifier() : String = {identifier}
def getContent() : String = {content}
}
and a simple subclass
package server
class SubContent(identifier:String, content:String) extends Content(identifier, content+"XXX")){
override def getContent():String = {
println(content)
super.getContent
}
}
What's really strange is that in the subclass there are duplicates of the superclass attributes, so if i create a new object
var c = new SubContent("x","x")
the execution of
c.getContent
first prints out "x" (The valued provided to the subclass constructor), but returns "xXXX" (The value provided to the superclass constructor).
Is there any way to avoid this behavior? Basically what I'd like to have is that the subclass does not create its own attributes but rather just passes the parameters to the superclass.
It's doing exactly what you told it to do. You augmented the 2nd constructor parameter when passing it on to the superclass constructor and then you used the superclass' getContent to provide the value returned from the subclass' getContent.
The thing you need to be aware of is that constructor parameters (those not tied to properties because they're part of a case class or because they were declared with the val keyword) are in scope throughout the class body. The class' constructor is that part of its body that is outside any method. So references to constructor parameters in method bodies forces the constructor parameter to be stored in a field so it can have the necessary extent. Note that your println call in getContent is causing such a hidden constructor parameter field in this case.
Replying to comment "Is there an alternative way to define it in order to avoid this? Or at least, if I never refer to the parameters of the subclass constructors their fields will be allocated (Wasting memory)?":
If the only references to plain constructor parameters (*) is in the constructor proper (i.e., outside any method body, and val and var initializers don't qualify as method bodies) then no invisible field will be created to hold the constructor parameter.
However, If there's more you're trying to "avoid" than these invisible fields, I don't understand what you're asking.
(*) By "plain constructor parameters" I mean those not part of a case class and not bearing the val keyword.