why a ctor-like method is permitted?

L

Lee

A ctor-like method is permitted in java, for example

public class MyClass
{
public MyClass() {//ctor here}
public void MyClass() {
//not a ctor, but a regular method, but permitted. it can be
called
like MyClassInstance.MyClass();
}
};

I am curious how the two functions are distinguished? They have the
same signature, return type does not count. This syntax is not
permitted in C++. I don't see why this feature is even allowed in
java, a safer language. Any comment?

Thanks

Lee
 
L

lcan

Hi Lee,

Return type does count: any java method with a return type is NOT a ctor.

Regards,
--lc
 
T

Thomas Schodt

Lee said:
A ctor-like method is permitted in java, for example

public class MyClass
{
public MyClass() {//ctor here}
public void MyClass() {
//not a ctor, but a regular method, but permitted.
//it can be called like MyClassInstance.MyClass();
}
}

I am curious how the two functions are distinguished?

In the source file;

the constructor has this signature
MyClass()

the method has this signature
void MyClass()


In the class file, at bytecode level;

the constructor has this signature
void <init>( void )

the method has this signature
void MyClass( void )
They have the same signature
Nope.

return type does not count.

It does in the source file.
 
J

John C. Bollinger

Lee said:
A ctor-like method is permitted in java, for example

public class MyClass
{
public MyClass() {//ctor here}
public void MyClass() {
//not a ctor, but a regular method, but permitted. it can be
called
like MyClassInstance.MyClass();
}
};

I am curious how the two functions are distinguished? They have the
same signature, return type does not count. This syntax is not
permitted in C++. I don't see why this feature is even allowed in
java, a safer language. Any comment?

A constructor is invoked via an object instantiation expression, which
can always be distinguished by the use of the "new" operator. A method
is invoked via a method invocation expression, which has various forms
(but none of them ambiguous in this respect). As others have noted,
there are also different representations at the bytecode level.

John Bollinger
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top