Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hello can anyone answer this questi

Status
Not open for further replies.

Dilenger4

Programmer
Nov 28, 2001
13
0
0
US
Hello can anyone answer this question for me.
Ive been looking over this block of code below.


They say that the class defines a method not a constructor since it has a return value. The method happens to have the same name as the class but that is irrelevant.

So i have one question.

1.)If the method happens to have the same name as the class and it is returning a value then this should result in a complation error. How can this not.

Thanks.




public class MyClass{
long var;

public void MyClass(long param){var = param;}

public static void main(String[] args){
MyClass a,b;
a = new MyClass();
b = new MyClass(5);
}
}
 
First:

the reserved word "new" in front of a name as in
"new MyClass()" will cause the compiler to look for a constructor with the same name and the same amount and type of parameters (aka the same syntax).

A constructor should always be declared as:
public Constructorname (parameters) { code }

So, in your code you have for instance "a = new MyClass()", but you don't have a constructor MyClass, since you put the reserved word "void" in front of the constructorname.

Second:

Normally a methodname should begin with a small letter and a class- and constructorname with a capital letter. And normally you wouldn't name a method the same way as your constructor. But there is no hard rule that you can't do it.
So, your declaration "public void MyClass(...) {...}" gives raise to a method named MyClass. And this will not give a compilation error, since it is perfectly legal. But, you obviously should consult the method by giving a message like "MyClass(5)" and not by "a = new MyClass(5)".

Hope this helped.

Swamphen
 
Thanks for the help. This was one of those trick questions that they try and give you on the Java Programmer Exam. =C)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top