The constructor name and class name are the same in Java. What for?

Please give me a logical answer to the naming of the class constructor andwith the same name. Why can't we choose a different name than the class name for the constructor?

class Temp
{
   Temp()
   {

   }
};
+4
source share
3 answers

Because this syntax does not require new keywords. In addition, there is no good reason.

To minimize the number of new keywords, I did not use explicit syntax like this:

class X {
    constructor();
    destructor();
}

Instead, I chose ad syntax that reflected the use of constructors.

class X {
    X();
    ~X();

Perhaps it was too smart. [Design and evolution of C ++, 3.11.2 Designator designation]

+6
source

, , , . - ,

Temp t = Temp();

, constructor(), , , ?

+4

, ++, , , , (-). , , . Temp::Temp class Temp.

, . , :: ( -) type::type, :: - , , .

, , , . .

Historically, constructors evolved from factory functions that returned an initialized object of this type. This template, in which function names may be similar to types and constructors, is just conditional, it can still be seen in some languages. The current syntax comes from something like what you can see in JavaScript. Some early C ++ compilers (thinking about THINK C, unsure of the earliest versions of Cfront) did not consider constructors as members at all.

+1
source

Source: https://habr.com/ru/post/1533276/


All Articles