<p>Given a class and its constructor to be defined, what are some options of where to put them logically relative to each other? What are the pros and cons of each of them?</p>
<p>For example, is a class and its constructor syntactically related? Is one of them defined within another? Are they considered the same entity or different entities?</p>
<h3>Note</h3>
<p>This question is about the structural relations, in contrast to the syntactical details such as whether to use a symbol, a keyword or a special identifier. So it's more on the semantic side than syntactic. But I draw the exact line as &quot;structural relations&quot;, which may contain syntactic structures in the big picture (i.e. the relation between subentities such as the name and params of a constructor is not a relation between a constructor and a class, therefore not asked by this question), and semantic structures, but should not matter because they often match, and it avoids discussions such as whether a structure is only a syntactic sugar.</p>
<p>There are also various semantic structures, such as membership, inheritance. But they are usually a closed set. And the parts relevant to constructors are strongly related to each other and affects each other that may have to be addressed together, so not to be split. The parts irrelevant to constructors are just irrelevant and unhelpful to put constructors in.</p>

<constructors>
Options of the relationship between classes and constructors
CC BY-SA 4.0
2023-08-01T10:33:20.110Z
Do you mean syntactically, or something else?
kaya3
CC BY-SA 4.0
2023-08-01T10:42:46.147Z
@kaya3-supportthestrike Syntax could be a thing. But it's more about the structural relations, in contrast to the syntactic details such as whether to use a symbol, a keyword or a special identifier.
user23013
CC BY-SA 4.0
2023-08-01T11:40:16.937Z
Surely the structural relation is that each class has a constructor, or alternatively each class has one or more constructors?
kaya3
CC BY-SA 4.0
2023-08-01T11:51:39.623Z
@kaya3-supportthestrike Not necessarily. The `Never` type by definition shouldn't have a constructor. More generally, an enum (Rust-like) with n options should have n constructors
abel1502
CC BY-SA 4.0
2023-08-01T11:55:58.570Z
@kaya3-supportthestrike There are cases where the class *is* the constructor. See my answer. And that may have different interpretations that I'm not yet aware of. I started with "pros and cons of named constructors", and felt it doesn't worth a question after some thinking. But after a few days I think neither way is optimal, and there might be other ways I don't know, so here is this question.
user23013
CC BY-SA 4.0
2023-08-01T11:56:57.370Z
`Never` isn't a class, and neither are Rust's enums. And I don't think your pre-ES5 Javascript example demonstrates anything except that pre-ES5 Javascript did not have classes. Perhaps you did not actually mean to ask about classes, but about types in general.
kaya3
CC BY-SA 4.0
2023-08-01T12:12:25.693Z
@kaya3-supportthestrike We all know what it is, but could we not be so technical in a question not intended for a specific language? Surely it's just called a constructor, but it is obviously an attempt to imitate classes (alongside prototypes) in other languages, although someone may say it's a failed attempt as it moved away. If you want to be technical, in modern JavaScript, a class is a special kind of constructor function, does it make it weirder and make it more distinctive to be on the list?
user23013
CC BY-SA 4.0
2023-08-01T12:17:45.400Z
This is a Q&A site about a technical field, you *have* to be clear about what you're asking. If you say the word "class" then people will not think you are talking about types like `Never`, sum types, or so on, because those things are not classes. What do you expect to gain by *not* using terms correctly?
kaya3
CC BY-SA 4.0
2023-08-01T12:19:04.903Z
@kaya3-supportthestrike It is a class if the term is used in the sense of "type". Some languages have classes as a specific subcategory of types, but others make no distinction between those. What I would agree with, is that an enum isn't a struct - but so aren't primitive numerics, undiscriminated unions, function types, tuples and so on.
abel1502
CC BY-SA 4.0
2023-08-01T12:20:23.333Z
No, "class" does not mean "type" in a language-agnostic context, and the fact that some languages have type systems where all types are classes does not change that.
kaya3
CC BY-SA 4.0
2023-08-01T12:23:19.103Z
@kaya3-supportthestrike That's your subjective view, which is obviously not universally agreed upon, since there are even languages that claim otherwise. Also, for instance, in C++'s STL (llvm one, specifically) `std::variant` is a `class`, yet it has the semantics of a discriminated union and still logically needs as many constructors as it has options
abel1502
CC BY-SA 4.0
2023-08-01T12:28:13.563Z
@kaya3-supportthestrike There could be a correct term in a specific language, but languages often disagree with each other about the terms. It serves no purpose for a general question to distinguish between member functions and methods, and possibly other names such as procedures, subroutines. It's much more difficult to find authority for all languages in general. But even if there is an authority, it would surely disagree with a language specific term, especially for the weird things like the JavaScript type system. For `Never`, I don't think it is relevant to this question.
user23013
CC BY-SA 4.0
2023-08-01T12:35:07.297Z
I invite you to read [Wikipedia's article about classes](https://en.wikipedia.org/wiki/Class_(computer_programming)), which gives a language-agnostic definition in accordance with the understanding of classes shared by most people who will read your question. The fact that languages use terms inconsistently doesn't mean those terms lack meaning outside of specific languages. Classes are generally extensible via inheritance, and their methods are dynamically dispatched based on the object's class at runtime. (By the way, that's the language-agnostic difference between functions and methods.)
kaya3
CC BY-SA 4.0
2023-08-01T12:49:03.163Z
@kaya3-supportthestrike "A class is an extensible program-code-template for creating objects" (the JavaScript constructor is, and prototypes are also placed as its member) "providing initial values for state and implementations of behavior" (yes it can). In any case, the JavaScript class as defined by the keyword `class` is simply not-a-thing other than syntactical sugar in a language-agnostic context, so there is no point to say ES6 have classes if you argue the old versions don't, in a language-agnostic context.
user23013
CC BY-SA 4.0
2023-08-01T12:57:56.470Z
I'm not changing the question to "types", because for any type that is not a class in a language using a familiar type system and common terms, it is almost always irrelevant to this kind of constructor. I don't intend for anyone to talk about types like "Never, sum types, or so on", to be specific.
user23013
CC BY-SA 4.0
2023-08-01T13:01:17.423Z
Javascript constructor functions are not classes; they can be used to create classes, but this requires the user to implement the features of classes (particularly inheritance) themselves, because constructor functions don't have those features. In contrast, Javascript's classes have inheritance, `super`, private fields and so on. They aren't exactly syntax sugar, but even if they were then the desugared form of a class would still involve more than just the declaration of a constructor function. So it makes perfect sense to say that constructor functions aren't classes.
kaya3
CC BY-SA 4.0
2023-08-01T13:03:26.873Z
That's fine, if you want your question to be about classes then say classes. But then why bring up `Never` and Rust-style enums in the comments, if they aren't supposed to be included in your question? And why argue that "type" and "class" are synonyms in a language-agnostic setting if your question *does* intend to make a distinction between them?
kaya3
CC BY-SA 4.0
2023-08-01T13:09:06.500Z
@kaya3-supportthestrike Someone else brought them up. I only mentioned they are irrelevant.
user23013
CC BY-SA 4.0
2023-08-01T13:15:24.000Z
Oh! My apologies, I completely didn't notice that I was responding to two different people! I have gotten the wrong end of the stick and made a fool of myself.
kaya3
CC BY-SA 4.0
2023-08-01T18:57:41.557Z
I think this question is too vague to be a good fit for the Q&A format. The “relationship” between classes and constructors could mean any number of things. Syntax? Semantics? Moreover, the question doesn’t even seem to ask for a discussion of tradeoffs, merely possibilities, but surely there are infinitely many possible answers to some of these questions.
Alexis King
CC BY-SA 4.0
2023-08-01T22:55:04.333Z
@AlexisKing I have edited some information in the comments into the question. It's "structural relationship". The question also has "what are the pros and cons of each of them" which means tradeoffs. Supposedly it is not for options with no pros at all. I consider the JavaScript example in the answer a nice try, but probably failed and turned ugly. Does it make a step to a better design which solved its problems, or is it a broken window to attract more ugly examples? I hope for the former, but I'm not expected to prove it will happen unless I already know the ultimate answer.
user23013
CC BY-SA 4.0
2023-08-03T16:20:25.883Z
Why should the structural relationship with the constructor be any different from the relationship with any other methods? While the constructor may have a special role, I don't think that necessitates a different syntactic relationship.
Barmar
CC BY-SA 4.0
2023-08-06T13:02:17.643Z
@Barmar in most languages, they have special syntactic rules and the compiler does completely different things there.
feldentm
CC BY-SA 4.0
2023-08-06T14:08:21.513Z
@feldentm Do they? Mostly it seems to be just a distinguished function name: `constructor` in JS, `__init__` in Python, `__construct` in PHP.
Barmar
CC BY-SA 4.0
2023-08-07T16:04:41.260Z
@Barmar all of your languages use protoyping which is not really OO and all of them are scripting languages.
feldentm
CC BY-SA 4.0
2023-08-07T16:07:10.327Z
@feldentm Only JS is prototype-based, although that's mostly hidden when you use ES6 class syntax. I'm not sure how being a scripting language is relevant.
Barmar
<p>While the question tries to ignore semantics, it is actually not possible to answer the question without going into details there. The reason is that the goal of a constructor is to construct an object and this interacts with lots of other concepts implemented in a language.</p>
<h2>Can a constructor be separated from the type it construct?</h2>
<p>A function that constructs an object, but is not associated with the type is a factory method for that type and is not a constructor. The reason for this are constant fields. If your object declares a constant field, none of its functions is allowed to change its value. Obviously, this cannot be the case for a constructor, because then, constant fields could only hold default values or the only way to construct objects would be by doing a somewhat atomic initialization like C-style constructors.</p>
<p>Common ways to mark such functions are by giving it the enclosing type's name or a reserved name like <code>new</code>, <code>__init__</code> or similar.</p>
<h2>Scala Shorthands</h2>
<p>This observation can be taken as motivation for Scala's way of using the entire type's body as a constructor. This is very nice and concise if types have exactly one constructor. If they have multiple constructors, Scala has means to implement that, but it makes the code very confusing and requires a lot of discipline.
The main reason is that multiple constructors do not necessarily construct objects in the same order and it is usually not a good idea to use constant members before they have been initialized or half-initialized objects. It is, nonetheless, a good idea to initialize objects the same way in all constructors. It's just not always feasible.</p>
<h2>Detour: VTable Initialization</h2>
<p>Somewhere in the process of constructing an object, its VTable pointer needs to be set. This is required for type checks and calling its own member functions. If a constructor calls another function, that function may observe a semi-initialized object that could have uninitialized fields or constants could have values that they no longer have after construction. This can cause lots of issues. Hence, some languages do not allow such calls.</p>
<p>At least all languages I've ever seen do not expose the VTable pointer as a mutable field to the user. As such, it must be somehow set by the object constructing code. This can be implicitly done by the constructor or it can be done by the code constructing the object that calls the constructor. There, it can happen before or after the constructor call. All these alternatives lead to different semantics of the dynamic type information during the execution of a constructor.
Such differences do obviously not exist for regular functions.</p>
<h2>Super constructor calls &amp; special calling semantics (stacked static)</h2>
<p>Constructors have special calling semantics usually not available for other function definitions. They usually behave like stacked static functions with an implicit this. I.e. if you call <code>T.new</code> and T has a super class S, it will <strong>implicitly</strong> call <code>S.new</code> for you and both will get executed. Regular functions don't do that. It is, however, required to realize the information hiding concept.</p>
<p>Most languages will force you to make the super constructor calls before executing the body of your constructor. The pro's and con's of this can be discussed in a separate question. Super constructor calls almost always have special semantics and might do things that the type system would otherwise not allow.</p>
<h2>Scala shorthand field declaration</h2>
<p>As mentioned by other answers already, Scala uses it's the body is the constructor trick to allow you to declare constructor arguments as fields.
This is obviously only a good idea if your classes have a single constructor. I'm not aware of the exact rules in Scala 3 tbh. A simple example of the pro&amp;con is</p>
<pre><code>class T(val x : Int){
  def this() = {
    this(3)
  }

  override def toString = &quot;x=&quot; + x
}
</code></pre>
<h2>Tyr shorthand initialization</h2>
<p>Tyr bypasses Scala's drawbacks by restricting the shorthand to the initialization of the field leading to</p>
<pre><code>class T {
  val x : int
  new (x := x : int);
  new { x = 3 }
}
</code></pre>
<p>C++ has initialization syntax, too. There, it is used uniformly for super constructor calls and field initializers and uses a syntax like <code>:x(3)</code>.</p>
<h2>C shorthand initialization</h2>
<p>Some languages allow C-style record initializers to be used as constructors. If this were the only way to construct on object, such a language cannot be called object-oriented, because it conflicts with information hiding. In OOP languages, the user of a type should not even know which fields it defines.</p>

CC BY-SA 4.0
2023-08-06T13:49:37.280Z
2023-08-06T13:49:37.280Z
feldentm
<p>I like what <a href="https://docs.scala-lang.org/scala3/book/domain-modeling-tools.html#classes" rel="nofollow noreferrer">Scala</a> and <a href="https://kotlinlang.org/docs/classes.html#constructors" rel="nofollow noreferrer">Kotlin</a> do with constructors:</p>
<pre class="lang-scala prettyprint-override"><code>class FooBar(parameter: String, val field: Int, var mutableField: Float) { ... }

// Use like
FooBar(&quot;Hello world&quot;, 42, Float.NaN)
</code></pre>
<p>Other approaches just seem more verbose. Both languages let you add initialization code via <code>init { ... }</code> and additional constructors via <code>constructor(otherParameter: Boolean) : this(...) { ... }</code> or <code>def this(otherParameter: Boolean) = this(...) ...</code>, but for most classes I don't use them, I only need to construct the object and assign its fields.</p>
<p>This also alludes to the idea that a constructor is just a function which evaluates to an instance of the class. There's nothing stopping you from defining a function which looks identical to a class constructor but returns something different, in fact this is a common pattern in both languages:</p>
<pre class="lang-scala prettyprint-override"><code>sealed trait FooBar { ... }
private case class Foo(val value: String) extends FooBar
private case class Bar(val value: String) extends FooBar
private case class Default(val value: String) extends FooBar

object FooBar {
    def apply(value: String): FooBar =
        if value.startsWith(&quot;Foo&quot;) then
            Foo(value.stripPrefix(&quot;Foo&quot;))
        else if value.startsWith(&quot;Bar&quot;) then
            Bar(value.stripPrefix(&quot;Bar&quot;))
        else
            Default(value)
}
</code></pre>
<p>It's also how structures in languages without classes are defined</p>
<pre class="lang-rust prettyprint-override"><code>struct FooBar {
    parameter: String,
    field: i32
}
</code></pre>
<pre class="lang-hs prettyprint-override"><code>data FooBar = FooBar { parameter: String, field: Int }
</code></pre>
<pre class="lang-c prettyprint-override"><code>typedef struct {
    const char* parameter,
    int field
} foo_bar;
</code></pre>
<p>and a class is just a structure with methods and subtyping.</p>

CC BY-SA 4.0
2023-08-05T22:09:28.943Z
2023-08-05T22:09:28.943Z
tarzh
<p>After working on this problem for some time, I believe there are indeed 3 fundamentally different concepts under classes, constructors and functions. The basic answer would sound like a frame challenge to my own question: There are 3 different kinds of underlying things, which could possibly defined anywhere, without enforced structural relations. Specifically, in a theoretical new language, one might be able to define a constructor for a class anywhere, with a syntax specifying which class it is constructing.</p>
<p>But it's reasonable for languages to want to unify them, because they are very related. A language could define 3 interfaces on the entity under the same name, while still allowing defining something with 1 interface elsewhere. The problem is how to define the 3 interfaces together, to avoid inconsistency with the versions traditionally with 1 interface.</p>
<p>In this answer, &quot;interfaces&quot; refer to ways of dealing with an entity in the interpreter or compiler. It may or may not be real interfaces in the language itself, and in the interpreter or compiler's language.</p>
<h2>The different interfaces</h2>
<p>Actually, there are not only 3 different concepts under them. But only the observable effects matter the most. The observable characteristics to make them different are:</p>
<ul>
<li>A type could correspond to multiple different routines to construct an object in it. It could be used in variable declaration, type hinting and some other places, where constructors might not be appropriate. But the important point is, to make sure the semantic of the same type at such places identical, even if we use constructors to refer to types.</li>
<li>A constructor could be called in other constructors in a way slightly different from function calls. It's more like creating a scope in a function body, where a scope could contain another scope, but the creation of one scope should not be invoked multiple times, at least if without deconstructing in between.</li>
<li>A function could extract a part of the scope as the return value, and choose what to return, not like the constructors where the returned value is already defined as <code>this</code> with a specific type on entry.</li>
</ul>
<p>So it's like, a constructor allows entering a scope, a function allows exiting a scope and extract some of its content, and a type allows marking two scopes the same, drawing a DAG. We may provide some of their characteristics to others after some unification. But for now, we could think them the core features of constructors, functions and types, and they have other features only by implementing or calling the others.</p>
<h2>The distractions</h2>
<p>If a property is unobservable from outside, it's better to start with providing all the options in every case, instead of unification. It could be useful to unify the body of constructors with normal functions, because sometimes we change something between constructors and normal functions, for their observable effects, and don't think the internal code makes much logical difference. But for unobservable properties such as the syntax in a block of code, it's easier to just always keep what is firstly written, and only unify the observable properties to support all the options in the unobservable properties. Examples are:</p>
<ul>
<li>Whether the block of code is list-style or function-style, whether type specifier are required, whether a <code>this.</code> prefix is needed, etc. A list-style block of code is most relevant to class definition and initialization, but a function could potentially also just return a list.</li>
<li>How a constructor is calling other constructors. A constructor exposes an interface to be called as an constructor. But how it calls other constructors, and the details such as the execution order and <a href="https://stackoverflow.com/q/962132/3998030">how virtual functions are handled</a>, while being like special properties of constructors, are generally hidden. Actually it's not very different from functions initializing local variables.</li>
<li>Whether the return value is allocated locally or dynamically. And while not technically unobservable, the C++ way of deciding this by the presence or absence of the <code>new</code> operator should also be irrelevant to whether it's a new object or returned from a normal function.</li>
<li>The choice of inclusion of the parameter list as a tuple with named elements elsewhere.</li>
</ul>
<p>Some of the options are most relevant to only one of constructors, functions and types. This led to many languages implementing them for one kind of entity as a special case, making them like inherent properties of that kind of entity. But they could have valid semantics for other kinds of entity, only less useful.</p>
<p>The observables need unification the most, but it's easy for someone to notice the unobservables, unify them and think it's a big advance. But that's actually not very helpful, and may make it more difficult to unify the observables, so some existing languages doing these and languages learning from them tend to move away.</p>
<ul>
<li>The code in a constructor in many languages is very different from a factory function, which is dissatisfactory. So someone may want to make every constructor like a normal function. But that's unnecessary. If it's just for having <code>this</code> or not in the body, it's better to allow any function to be marked as a constructor or syntactically like a constructor to a class, even if it's logically just a normal function.</li>
<li>Many constructors are just setting each of the member variables, seemingly just repeating the member variable declarations. So someone may want to merge them, making it difficult to have multiple constructors for the same type. But the problem is simply because it requires every such construct to generate both a type and a constructor. If we consider it only a syntax style, we could also allow using it to define only a constructor, optionally throwing away the type part, or only refer to a type without considering its constructor. It may also either enforce the use of <code>this.</code>, or make it difficult to define local variables, because the function-style code seems more general. It would be much better to just default to the traditional class definitions or other list-like definitions, and allow function-style code as an add-on.</li>
<li>In many languages, class names could be used like a function for constructing an object. This makes seemingly nowhere to put other constructors for the same type. But nowhere says the other constructors cannot be just an alias of the original type if used as a type.</li>
</ul>
<p>Some of what I devises may seem overly complex, but they could be considered thought experiments for now.</p>
<h2>Possible unification</h2>
<p>Without the distractions, we could just use what I devises before for the observables: A way to enter a scope, a way to exit a scope and extract some of its content, and a way to mark two types equal, with specifiers to extend the previous type or inhibit the previous constructor. That's it. But some notes:</p>
<ul>
<li>If the code exits a scope somewhere, but we consider its properties as if we use it for entering a scope, only the extracted content matters. That is, a constructor could be inside a function, and still export the information for calling from another constructor depending on it. The function could get the constructor interface, for telling how much space should be allocated for the object it is going to return, and another constructor could call it like a constructor.</li>
<li>Most of a class could be defined by its members, which could be in the body of a constructor. It indeed should be in constructors if we consider the most important part of a type a way to mark two types equal, or specifying other relations between classes, separate from entering a scope.</li>
<li>The return type of any function is a type. We could use that type if we use functions as types.</li>
</ul>
<p>More work is needed to define the exact syntax and semantic. But basically, anything that could be used like a function is a function. But some of the could return the construction of an object, possibly starting from another function that is used as a constructor. The construction of object could also define a type.</p>
<p>This is not about how constructor, functions and types are similar or different, but how their previous functionalities are used together, merging to a single kind of entity with the 3 interfaces.</p>
<p>This makes it not so bad to have the previous distractions that link another property to a specific type of entity back, so the attempts of removing them were only thought experiments, because the other variants also exist somewhere. For example, it's not so bad to make constructors always list-style and functions always function-style, because you could just include an instance of another type of entity to contain code with the other syntax style. This may recreate footguns for the next person thinking about this problem only taking references to the existing designs and not the reasoning, but some language designers may think this the most practical.</p>
<h2>So, what's the relationship between classes and constructors?</h2>
<p>In this design, one could say they are not very related in structure, as a constructor for a class could appear anywhere. But it is only anywhere inside functions, if it is not for constructing one object without reusing the constructor. A class could have its members defined in a constructor, but logically it's the return type of a function, outside the body of the function. There is a hidden level of functions between classes and constructors in the traditional design, which might be a source of confusion. I added functions among the two, and chose a seemingly unindicative characteristic of exiting a scope for functions, to note its existence.</p>
<p>Many of the difficulties of mixing code of different styles, which sparked ideas of unification, comes from premature unification of one of the two with functions. Many problems could be solved easily if the level of functions is explicit and it is also explicit that this won't block other interfaces. Some problems are more difficult than others, but could have better chance using advanced features like templates or generics on functions, rather than special cases in class definitions. Distinguishing between a basic call and a full call like other constructors calling no constructors or the default constructor, is something I don't know where to put in this answer, but it could be done on functions using a completely new feature if it is deemed useful.</p>
<p>So, while it does say classes and constructors are not very related in structure, it also points out the intuitive idea of &quot;not very related&quot; contain superficial relations between them and functions. So it is a different relationship from the default &quot;unrelated&quot;.</p>
<h2>Java</h2>
<p>A surprising language that is close to this design is Java. While other languages began to learn how useful it is to have anonymous functions or lambda functions, Java always had anonymous classes. Most programmers would probably use the traditional ways writing a factory method, but if you want, you could return an object of an anonymous subclass, and write the real useful code in its constructor, to allow not changing much of the code when turning a constructor to a factory method and back. It also conveniently has the feature of &quot;instance initialization blocks&quot;, which is effectively allowing mixing function-style code in a list-style definition, to remove boilerplate from conventional constructors.</p>
<p>This example is modified from <a href="https://stackoverflow.com/a/8765054/3998030">this SO answer</a>:</p>
<pre class="lang-java prettyprint-override"><code>public static JPanel JPanelFactory() {
    return new JPanel() {{
        setSize(100,100);
        setLocation(50,50);
        setBackground(Color.red);
    }};
}
</code></pre>
<p>It would look more acceptable if the outer braces and <code>return</code> could be omitted, like what is done in attempts to unify named and lambda functions in some languages, and the <code>new</code> also could be omitted like many languages. A language could also make the type specifier optional if the type is clear, or type names in construction optional if the type is already specified, or both, to remove the duplicated type name.</p>
<p>It doesn't expose the constructor interface, or at least not in a straightforward way, but it could in a hypothetical new language. It is more like a subclass, but after the constructor interface is exposed, it makes sense to change it to be also possible to be in an identical class. From there, we could change traditional constructors to be also in this style.</p>
<p>Java is considered restrictive by many people, and I don't think it is designed for changing constructors to something else, but it had the exact right features to make it close to move constructors anywhere freely and also mix with the class definition itself without backfire. Actually every relevant feature here, in Java or as I described, seems to be an obvious improvement, and it only need piecing everything together. Some other languages might be intended for making factory functions like a constructor, by removing features, ending up much more restrictive than Java in this specific case, which is probably an example of everything should be made as simple as possible, but no simpler.</p>

CC BY-SA 4.0
2023-08-13T16:01:41.897Z
2023-08-13T16:01:41.897Z
user23013
<h2>Constructor as a special member function, called using the class name directly</h2>
<p>Sometimes in the formal definition, constructors are just constructors, but they are defined like a member function. In other cases they are really a member function with a special name. They are called using <code>ClassName(params)</code> without a specific name of the constructor, sometimes with a keyword <code>new</code>, and sometimes it could mean different things depending on whether there is a <code>new</code>.</p>
<p>Some examples:</p>
<pre class="lang-cpp prettyprint-override"><code>class T{
public:
    T(){
        //...
    }
};
</code></pre>
<pre class="lang-python prettyprint-override"><code>class T:
    def __init__(self):
        pass #...
</code></pre>
<pre class="lang-php prettyprint-override"><code>class T{
    function __construct(){
        //...
    }
}
</code></pre>
<p>It makes classes appeared like functions, which could be called to construct the object, and also allowed using the same class name to refer to the class. But it must be in a specific place, and has special cases, so that it requires changing the code if someone want to move a constructor to elsewhere to be called differently.</p>
<h2>Named constructors</h2>
<p>Some languages such as Delphi (Object Pascal) have named constructors. You could have multiple constructors in different names. Constructors are usually called by assigning <code>ClassName.ConstructorName(params)</code> to a variable of type <code>ClassName</code>.</p>
<p>(Delphi also has named destructors, which is much more unthinkable.)</p>
<pre class="lang-pascal prettyprint-override"><code>type
    T = class(TObject)
    public
        constructor Create();
    end;
constructor T.Create();
begin
    //...
end;
</code></pre>
<p>The pro is you could distinguish different constructors by something other than the parameter list. But it also must be in the class, and requires changing the code if moved elsewhere.</p>
<h2>Constructor defines the type</h2>
<p>The old style JavaScript classes are defined by a constructor, which is just a function. Other members are also set in the constructor. (It also has prototypes which are set to the constructor outside the constructor.) It creates an object whenever the keyword <code>new</code> is prefixed to the function call.</p>
<p>It works like creating an object using a general routine, then call the constructor like it was the object's member.</p>
<p>It removed a separate type of entity from the declaration, but enforced a separate usage. And without a special type of scope, it's difficult to derive from the type but only use some part of the initialization code in its construction. It also adds more discrepancies, like using <code>this.</code> instead of <code>var</code>, and cannot define variables without a initial value. A more traditional syntax for classes are reintroduced later for various reasons.</p>
<h2>No constructors</h2>
<p>Some languages don't have a special concept of constructors. All objects are created in a general way. But you could have something like a constructor, by using a function to create object and initialize the properties.</p>
<p>The &quot;constructor&quot; would be a normal function, which calls a general routine to actually create the object.</p>
<p>It makes user-defined constructors really identical to a function, without any irregularities. It also allowed the function to be changed to return different subclasses. But classes must be referred using different names. And it could make default values special and may not be in a valid state.</p>
<h2>Conclusion</h2>
<p>I think there is a trend to unify the usage of class constructions and normal functions. But languages disagree about how they should be unified, and all have irregularities in different places. JavaScript seems closest, but it is also the most impractical. I think there are indeed some different types of underlying entities or concepts not to be unified. And that's also why I'm looking forward for more options.</p>

CC BY-SA 4.0
2023-08-01T10:09:53.613Z
2023-08-01T11:24:25.467Z
2023-08-01T11:24:25.467Z
user23013
CC BY-SA 4.0
2023-08-06T14:41:37.117Z
Rust doesn't have constructors, but it also requires objects to be initialized fully all at once
Seggan
# Options of the relationship between classes and constructors
Posted by: username_0 on 2023-08-01
Given a class and its constructor to be defined, what are some options of where to put them logically relative to each other? What are the pros and cons of each of them?

For example, is a class and its constructor syntactically related? Is one of them defined within another? Are they considered the same entity or different entities?

### Note

This question is about the structural relations, in contrast to the syntactical details such as whether to use a symbol, a keyword or a special identifier. So it's more on the semantic side than syntactic. But I draw the exact line as "structural relations", which may contain syntactic structures in the big picture (i.e. the relation between subentities such as the name and params of a constructor is not a relation between a constructor and a class, therefore not asked by this question), and semantic structures, but should not matter because they often match, and it avoids discussions such as whether a structure is only a syntactic sugar.

There are also various semantic structures, such as membership, inheritance. But they are usually a closed set. And the parts relevant to constructors are strongly related to each other and affects each other that may have to be addressed together, so not to be split. The parts irrelevant to constructors are just irrelevant and unhelpful to put constructors in.
**Tags:** constructors
> **Comments:**
> **username_1**: Do you mean syntactically, or something else?  
> **username_0**: @kaya3-supportthestrike Syntax could be a thing. But it's more about the structural relations, in contrast to the syntactic details such as whether to use a symbol, a keyword or a special identifier.  
> **username_1**: Surely the structural relation is that each class has a constructor, or alternatively each class has one or more constructors?  
> **username_2**: @kaya3-supportthestrike Not necessarily. The `Never` type by definition shouldn't have a constructor. More generally, an enum (Rust-like) with n options should have n constructors  
> **username_0**: @kaya3-supportthestrike There are cases where the class *is* the constructor. See my answer. And that may have different interpretations that I'm not yet aware of. I started with "pros and cons of named constructors", and felt it doesn't worth a question after some thinking. But after a few days I think neither way is optimal, and there might be other ways I don't know, so here is this question.  
> **username_1**: `Never` isn't a class, and neither are Rust's enums. And I don't think your pre-ES5 Javascript example demonstrates anything except that pre-ES5 Javascript did not have classes. Perhaps you did not actually mean to ask about classes, but about types in general.  
> **username_0**: @kaya3-supportthestrike We all know what it is, but could we not be so technical in a question not intended for a specific language? Surely it's just called a constructor, but it is obviously an attempt to imitate classes (alongside prototypes) in other languages, although someone may say it's a failed attempt as it moved away. If you want to be technical, in modern JavaScript, a class is a special kind of constructor function, does it make it weirder and make it more distinctive to be on the list?  
> **username_1**: This is a Q&A site about a technical field, you *have* to be clear about what you're asking. If you say the word "class" then people will not think you are talking about types like `Never`, sum types, or so on, because those things are not classes. What do you expect to gain by *not* using terms correctly?  
> **username_2**: @kaya3-supportthestrike It is a class if the term is used in the sense of "type". Some languages have classes as a specific subcategory of types, but others make no distinction between those. What I would agree with, is that an enum isn't a struct - but so aren't primitive numerics, undiscriminated unions, function types, tuples and so on.  
> **username_1**: No, "class" does not mean "type" in a language-agnostic context, and the fact that some languages have type systems where all types are classes does not change that.  
> **username_2**: @kaya3-supportthestrike That's your subjective view, which is obviously not universally agreed upon, since there are even languages that claim otherwise. Also, for instance, in C++'s STL (llvm one, specifically) `std::variant` is a `class`, yet it has the semantics of a discriminated union and still logically needs as many constructors as it has options  
> **username_0**: @kaya3-supportthestrike There could be a correct term in a specific language, but languages often disagree with each other about the terms. It serves no purpose for a general question to distinguish between member functions and methods, and possibly other names such as procedures, subroutines. It's much more difficult to find authority for all languages in general. But even if there is an authority, it would surely disagree with a language specific term, especially for the weird things like the JavaScript type system. For `Never`, I don't think it is relevant to this question.  
> **username_1**: I invite you to read [Wikipedia's article about classes](https://en.wikipedia.org/wiki/Class_(computer_programming)), which gives a language-agnostic definition in accordance with the understanding of classes shared by most people who will read your question. The fact that languages use terms inconsistently doesn't mean those terms lack meaning outside of specific languages. Classes are generally extensible via inheritance, and their methods are dynamically dispatched based on the object's class at runtime. (By the way, that's the language-agnostic difference between functions and methods.)  
> **username_0**: @kaya3-supportthestrike "A class is an extensible program-code-template for creating objects" (the JavaScript constructor is, and prototypes are also placed as its member) "providing initial values for state and implementations of behavior" (yes it can). In any case, the JavaScript class as defined by the keyword `class` is simply not-a-thing other than syntactical sugar in a language-agnostic context, so there is no point to say ES6 have classes if you argue the old versions don't, in a language-agnostic context.  
> **username_0**: I'm not changing the question to "types", because for any type that is not a class in a language using a familiar type system and common terms, it is almost always irrelevant to this kind of constructor. I don't intend for anyone to talk about types like "Never, sum types, or so on", to be specific.  
> **username_1**: Javascript constructor functions are not classes; they can be used to create classes, but this requires the user to implement the features of classes (particularly inheritance) themselves, because constructor functions don't have those features. In contrast, Javascript's classes have inheritance, `super`, private fields and so on. They aren't exactly syntax sugar, but even if they were then the desugared form of a class would still involve more than just the declaration of a constructor function. So it makes perfect sense to say that constructor functions aren't classes.  
> **username_1**: That's fine, if you want your question to be about classes then say classes. But then why bring up `Never` and Rust-style enums in the comments, if they aren't supposed to be included in your question? And why argue that "type" and "class" are synonyms in a language-agnostic setting if your question *does* intend to make a distinction between them?  
> **username_0**: @kaya3-supportthestrike Someone else brought them up. I only mentioned they are irrelevant.  
> **username_1**: Oh! My apologies, I completely didn't notice that I was responding to two different people! I have gotten the wrong end of the stick and made a fool of myself.  
> **username_3**: I think this question is too vague to be a good fit for the Q&A format. The “relationship” between classes and constructors could mean any number of things. Syntax? Semantics? Moreover, the question doesn’t even seem to ask for a discussion of tradeoffs, merely possibilities, but surely there are infinitely many possible answers to some of these questions.  
> **username_0**: @AlexisKing I have edited some information in the comments into the question. It's "structural relationship". The question also has "what are the pros and cons of each of them" which means tradeoffs. Supposedly it is not for options with no pros at all. I consider the JavaScript example in the answer a nice try, but probably failed and turned ugly. Does it make a step to a better design which solved its problems, or is it a broken window to attract more ugly examples? I hope for the former, but I'm not expected to prove it will happen unless I already know the ultimate answer.  
> **username_4**: Why should the structural relationship with the constructor be any different from the relationship with any other methods? While the constructor may have a special role, I don't think that necessitates a different syntactic relationship.  
> **username_5**: @Barmar in most languages, they have special syntactic rules and the compiler does completely different things there.  
> **username_4**: @feldentm Do they? Mostly it seems to be just a distinguished function name: `constructor` in JS, `__init__` in Python, `__construct` in PHP.  
> **username_5**: @Barmar all of your languages use protoyping which is not really OO and all of them are scripting languages.  
> **username_4**: @feldentm Only JS is prototype-based, although that's mostly hidden when you use ES6 class syntax. I'm not sure how being a scripting language is relevant.  
---
## 4 answers
### Answer by username_5 on 2023-08-06. Score: 4
While the question tries to ignore semantics, it is actually not possible to answer the question without going into details there. The reason is that the goal of a constructor is to construct an object and this interacts with lots of other concepts implemented in a language.
Can a constructor be separated from the type it construct?
A function that constructs an object, but is not associated with the type is a factory method for that type and is not a constructor. The reason for this are constant fields. If your object declares a constant field, none of its functions is allowed to change its value. Obviously, this cannot be the case for a constructor, because then, constant fields could only hold default values or the only way to construct objects would be by doing a somewhat atomic initialization like C-style constructors.
Common ways to mark such functions are by giving it the enclosing type's name or a reserved name like new, __init__ or similar.
Scala Shorthands
This observation can be taken as motivation for Scala's way of using the entire type's body as a constructor. This is very nice and concise if types have exactly one constructor. If they have multiple constructors, Scala has means to implement that, but it makes the code very confusing and requires a lot of discipline.
The main reason is that multiple constructors do not necessarily construct objects in the same order and it is usually not a good idea to use constant members before they have been initialized or half-initialized objects. It is, nonetheless, a good idea to initialize objects the same way in all constructors. It's just not always feasible.
Detour: VTable Initialization
Somewhere in the process of constructing an object, its VTable pointer needs to be set. This is required for type checks and calling its own member functions. If a constructor calls another function, that function may observe a semi-initialized object that could have uninitialized fields or constants could have values that they no longer have after construction. This can cause lots of issues. Hence, some languages do not allow such calls.
At least all languages I've ever seen do not expose the VTable pointer as a mutable field to the user. As such, it must be somehow set by the object constructing code. This can be implicitly done by the constructor or it can be done by the code constructing the object that calls the constructor. There, it can happen before or after the constructor call. All these alternatives lead to different semantics of the dynamic type information during the execution of a constructor.
Such differences do obviously not exist for regular functions.
Super constructor calls & special calling semantics (stacked static)
Constructors have special calling semantics usually not available for other function definitions. They usually behave like stacked static functions with an implicit this. I.e. if you call T.new and T has a super class S, it will implicitly call S.new for you and both will get executed. Regular functions don't do that. It is, however, required to realize the information hiding concept.
Most languages will force you to make the super constructor calls before executing the body of your constructor. The pro's and con's of this can be discussed in a separate question. Super constructor calls almost always have special semantics and might do things that the type system would otherwise not allow.
Scala shorthand field declaration
As mentioned by other answers already, Scala uses it's the body is the constructor trick to allow you to declare constructor arguments as fields.
This is obviously only a good idea if your classes have a single constructor. I'm not aware of the exact rules in Scala 3 tbh. A simple example of the pro&con is
class T(val x : Int){
  def this() = {
    this(3)
  }

  override def toString = "x=" + x
}

Tyr shorthand initialization
Tyr bypasses Scala's drawbacks by restricting the shorthand to the initialization of the field leading to
class T {
  val x : int
  new (x := x : int);
  new { x = 3 }
}

C++ has initialization syntax, too. There, it is used uniformly for super constructor calls and field initializers and uses a syntax like :x(3).
C shorthand initialization
Some languages allow C-style record initializers to be used as constructors. If this were the only way to construct on object, such a language cannot be called object-oriented, because it conflicts with information hiding. In OOP languages, the user of a type should not even know which fields it defines.
---
### Answer by username_6 on 2023-08-05. Score: 3
I like what Scala and Kotlin do with constructors:
class FooBar(parameter: String, val field: Int, var mutableField: Float) { ... }

// Use like
FooBar("Hello world", 42, Float.NaN)

Other approaches just seem more verbose. Both languages let you add initialization code via init { ... } and additional constructors via constructor(otherParameter: Boolean) : this(...) { ... } or def this(otherParameter: Boolean) = this(...) ..., but for most classes I don't use them, I only need to construct the object and assign its fields.
This also alludes to the idea that a constructor is just a function which evaluates to an instance of the class. There's nothing stopping you from defining a function which looks identical to a class constructor but returns something different, in fact this is a common pattern in both languages:
sealed trait FooBar { ... }
private case class Foo(val value: String) extends FooBar
private case class Bar(val value: String) extends FooBar
private case class Default(val value: String) extends FooBar

object FooBar {
    def apply(value: String): FooBar =
        if value.startsWith("Foo") then
            Foo(value.stripPrefix("Foo"))
        else if value.startsWith("Bar") then
            Bar(value.stripPrefix("Bar"))
        else
            Default(value)
}

It's also how structures in languages without classes are defined
struct FooBar {
    parameter: String,
    field: i32
}

data FooBar = FooBar { parameter: String, field: Int }

typedef struct {
    const char* parameter,
    int field
} foo_bar;

and a class is just a structure with methods and subtyping.
---
### Answer by username_0 on 2023-08-01. Score: 3
Constructor as a special member function, called using the class name directly
Sometimes in the formal definition, constructors are just constructors, but they are defined like a member function. In other cases they are really a member function with a special name. They are called using ClassName(params) without a specific name of the constructor, sometimes with a keyword new, and sometimes it could mean different things depending on whether there is a new.
Some examples:
class T{
public:
    T(){
        //...
    }
};

class T:
    def __init__(self):
        pass #...

class T{
    function __construct(){
        //...
    }
}

It makes classes appeared like functions, which could be called to construct the object, and also allowed using the same class name to refer to the class. But it must be in a specific place, and has special cases, so that it requires changing the code if someone want to move a constructor to elsewhere to be called differently.
Named constructors
Some languages such as Delphi (Object Pascal) have named constructors. You could have multiple constructors in different names. Constructors are usually called by assigning ClassName.ConstructorName(params) to a variable of type ClassName.
(Delphi also has named destructors, which is much more unthinkable.)
type
    T = class(TObject)
    public
        constructor Create();
    end;
constructor T.Create();
begin
    //...
end;

The pro is you could distinguish different constructors by something other than the parameter list. But it also must be in the class, and requires changing the code if moved elsewhere.
Constructor defines the type
The old style JavaScript classes are defined by a constructor, which is just a function. Other members are also set in the constructor. (It also has prototypes which are set to the constructor outside the constructor.) It creates an object whenever the keyword new is prefixed to the function call.
It works like creating an object using a general routine, then call the constructor like it was the object's member.
It removed a separate type of entity from the declaration, but enforced a separate usage. And without a special type of scope, it's difficult to derive from the type but only use some part of the initialization code in its construction. It also adds more discrepancies, like using this. instead of var, and cannot define variables without a initial value. A more traditional syntax for classes are reintroduced later for various reasons.
No constructors
Some languages don't have a special concept of constructors. All objects are created in a general way. But you could have something like a constructor, by using a function to create object and initialize the properties.
The "constructor" would be a normal function, which calls a general routine to actually create the object.
It makes user-defined constructors really identical to a function, without any irregularities. It also allowed the function to be changed to return different subclasses. But classes must be referred using different names. And it could make default values special and may not be in a valid state.
Conclusion
I think there is a trend to unify the usage of class constructions and normal functions. But languages disagree about how they should be unified, and all have irregularities in different places. JavaScript seems closest, but it is also the most impractical. I think there are indeed some different types of underlying entities or concepts not to be unified. And that's also why I'm looking forward for more options.
> **Comments:**
> **username_7** (2023-08-06): Rust doesn't have constructors, but it also requires objects to be initialized fully all at once  
---
### Answer by username_0 on 2023-08-13. Score: 0
After working on this problem for some time, I believe there are indeed 3 fundamentally different concepts under classes, constructors and functions. The basic answer would sound like a frame challenge to my own question: There are 3 different kinds of underlying things, which could possibly defined anywhere, without enforced structural relations. Specifically, in a theoretical new language, one might be able to define a constructor for a class anywhere, with a syntax specifying which class it is constructing.
But it's reasonable for languages to want to unify them, because they are very related. A language could define 3 interfaces on the entity under the same name, while still allowing defining something with 1 interface elsewhere. The problem is how to define the 3 interfaces together, to avoid inconsistency with the versions traditionally with 1 interface.
In this answer, "interfaces" refer to ways of dealing with an entity in the interpreter or compiler. It may or may not be real interfaces in the language itself, and in the interpreter or compiler's language.
The different interfaces
Actually, there are not only 3 different concepts under them. But only the observable effects matter the most. The observable characteristics to make them different are:

A type could correspond to multiple different routines to construct an object in it. It could be used in variable declaration, type hinting and some other places, where constructors might not be appropriate. But the important point is, to make sure the semantic of the same type at such places identical, even if we use constructors to refer to types.
A constructor could be called in other constructors in a way slightly different from function calls. It's more like creating a scope in a function body, where a scope could contain another scope, but the creation of one scope should not be invoked multiple times, at least if without deconstructing in between.
A function could extract a part of the scope as the return value, and choose what to return, not like the constructors where the returned value is already defined as this with a specific type on entry.

So it's like, a constructor allows entering a scope, a function allows exiting a scope and extract some of its content, and a type allows marking two scopes the same, drawing a DAG. We may provide some of their characteristics to others after some unification. But for now, we could think them the core features of constructors, functions and types, and they have other features only by implementing or calling the others.
The distractions
If a property is unobservable from outside, it's better to start with providing all the options in every case, instead of unification. It could be useful to unify the body of constructors with normal functions, because sometimes we change something between constructors and normal functions, for their observable effects, and don't think the internal code makes much logical difference. But for unobservable properties such as the syntax in a block of code, it's easier to just always keep what is firstly written, and only unify the observable properties to support all the options in the unobservable properties. Examples are:

Whether the block of code is list-style or function-style, whether type specifier are required, whether a this. prefix is needed, etc. A list-style block of code is most relevant to class definition and initialization, but a function could potentially also just return a list.
How a constructor is calling other constructors. A constructor exposes an interface to be called as an constructor. But how it calls other constructors, and the details such as the execution order and how virtual functions are handled, while being like special properties of constructors, are generally hidden. Actually it's not very different from functions initializing local variables.
Whether the return value is allocated locally or dynamically. And while not technically unobservable, the C++ way of deciding this by the presence or absence of the new operator should also be irrelevant to whether it's a new object or returned from a normal function.
The choice of inclusion of the parameter list as a tuple with named elements elsewhere.

Some of the options are most relevant to only one of constructors, functions and types. This led to many languages implementing them for one kind of entity as a special case, making them like inherent properties of that kind of entity. But they could have valid semantics for other kinds of entity, only less useful.
The observables need unification the most, but it's easy for someone to notice the unobservables, unify them and think it's a big advance. But that's actually not very helpful, and may make it more difficult to unify the observables, so some existing languages doing these and languages learning from them tend to move away.

The code in a constructor in many languages is very different from a factory function, which is dissatisfactory. So someone may want to make every constructor like a normal function. But that's unnecessary. If it's just for having this or not in the body, it's better to allow any function to be marked as a constructor or syntactically like a constructor to a class, even if it's logically just a normal function.
Many constructors are just setting each of the member variables, seemingly just repeating the member variable declarations. So someone may want to merge them, making it difficult to have multiple constructors for the same type. But the problem is simply because it requires every such construct to generate both a type and a constructor. If we consider it only a syntax style, we could also allow using it to define only a constructor, optionally throwing away the type part, or only refer to a type without considering its constructor. It may also either enforce the use of this., or make it difficult to define local variables, because the function-style code seems more general. It would be much better to just default to the traditional class definitions or other list-like definitions, and allow function-style code as an add-on.
In many languages, class names could be used like a function for constructing an object. This makes seemingly nowhere to put other constructors for the same type. But nowhere says the other constructors cannot be just an alias of the original type if used as a type.

Some of what I devises may seem overly complex, but they could be considered thought experiments for now.
Possible unification
Without the distractions, we could just use what I devises before for the observables: A way to enter a scope, a way to exit a scope and extract some of its content, and a way to mark two types equal, with specifiers to extend the previous type or inhibit the previous constructor. That's it. But some notes:

If the code exits a scope somewhere, but we consider its properties as if we use it for entering a scope, only the extracted content matters. That is, a constructor could be inside a function, and still export the information for calling from another constructor depending on it. The function could get the constructor interface, for telling how much space should be allocated for the object it is going to return, and another constructor could call it like a constructor.
Most of a class could be defined by its members, which could be in the body of a constructor. It indeed should be in constructors if we consider the most important part of a type a way to mark two types equal, or specifying other relations between classes, separate from entering a scope.
The return type of any function is a type. We could use that type if we use functions as types.

More work is needed to define the exact syntax and semantic. But basically, anything that could be used like a function is a function. But some of the could return the construction of an object, possibly starting from another function that is used as a constructor. The construction of object could also define a type.
This is not about how constructor, functions and types are similar or different, but how their previous functionalities are used together, merging to a single kind of entity with the 3 interfaces.
This makes it not so bad to have the previous distractions that link another property to a specific type of entity back, so the attempts of removing them were only thought experiments, because the other variants also exist somewhere. For example, it's not so bad to make constructors always list-style and functions always function-style, because you could just include an instance of another type of entity to contain code with the other syntax style. This may recreate footguns for the next person thinking about this problem only taking references to the existing designs and not the reasoning, but some language designers may think this the most practical.
So, what's the relationship between classes and constructors?
In this design, one could say they are not very related in structure, as a constructor for a class could appear anywhere. But it is only anywhere inside functions, if it is not for constructing one object without reusing the constructor. A class could have its members defined in a constructor, but logically it's the return type of a function, outside the body of the function. There is a hidden level of functions between classes and constructors in the traditional design, which might be a source of confusion. I added functions among the two, and chose a seemingly unindicative characteristic of exiting a scope for functions, to note its existence.
Many of the difficulties of mixing code of different styles, which sparked ideas of unification, comes from premature unification of one of the two with functions. Many problems could be solved easily if the level of functions is explicit and it is also explicit that this won't block other interfaces. Some problems are more difficult than others, but could have better chance using advanced features like templates or generics on functions, rather than special cases in class definitions. Distinguishing between a basic call and a full call like other constructors calling no constructors or the default constructor, is something I don't know where to put in this answer, but it could be done on functions using a completely new feature if it is deemed useful.
So, while it does say classes and constructors are not very related in structure, it also points out the intuitive idea of "not very related" contain superficial relations between them and functions. So it is a different relationship from the default "unrelated".
Java
A surprising language that is close to this design is Java. While other languages began to learn how useful it is to have anonymous functions or lambda functions, Java always had anonymous classes. Most programmers would probably use the traditional ways writing a factory method, but if you want, you could return an object of an anonymous subclass, and write the real useful code in its constructor, to allow not changing much of the code when turning a constructor to a factory method and back. It also conveniently has the feature of "instance initialization blocks", which is effectively allowing mixing function-style code in a list-style definition, to remove boilerplate from conventional constructors.
This example is modified from this SO answer:
public static JPanel JPanelFactory() {
    return new JPanel() {{
        setSize(100,100);
        setLocation(50,50);
        setBackground(Color.red);
    }};
}

It would look more acceptable if the outer braces and return could be omitted, like what is done in attempts to unify named and lambda functions in some languages, and the new also could be omitted like many languages. A language could also make the type specifier optional if the type is clear, or type names in construction optional if the type is already specified, or both, to remove the duplicated type name.
It doesn't expose the constructor interface, or at least not in a straightforward way, but it could in a hypothetical new language. It is more like a subclass, but after the constructor interface is exposed, it makes sense to change it to be also possible to be in an identical class. From there, we could change traditional constructors to be also in this style.
Java is considered restrictive by many people, and I don't think it is designed for changing constructors to something else, but it had the exact right features to make it close to move constructors anywhere freely and also mix with the class definition itself without backfire. Actually every relevant feature here, in Java or as I described, seems to be an obvious improvement, and it only need piecing everything together. Some other languages might be intended for making factory functions like a constructor, by removing features, ending up much more restrictive than Java in this specific case, which is probably an example of everything should be made as simple as possible, but no simpler.
---
