my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes constructor. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "constructor." Watch "constructor." New topic


Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
I am confused by the concept of Constructor when I got this question:
1. class Mystery {
2. String s;
3. public static void main(String args[]) {
4. Mystery m = new Mystery();
5. m.go();
6. }
7. void Mystery() {
8. s = "Constructor";
9. }
10. void go() {
11. System.out.println(s);
12. }
13. }
I expected the answer is Constructor, but the it prints out null. My understanding is when new Mystery, the "Constructor" will be passed to s, then go method can print it out.
When I tried to modify the code and want to print "Constructor" out, but got complie error with cannot resolve symbol construcor Mystery.
class Mystery {
String s;

void Mystery(String s) {
this.s = s;
public static void main(String args[]) {
Mystery m = new Mystery("an");
System.out.println("m.s is "+m.s);

void go(String s) {
i must missing something. please help. Thanks.
Uvnik Gupta
Ranch Hand

Joined: Jul 24, 2000
Posts: 32
Remove the return type "void". Cunstructors don't have return types.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Thanks a lot, Uvnik!
I didn't notice that it is not a constructor.
Thanks again.
Ranch Hand

Joined: Jun 28, 2000
Posts: 93
Hi mikeliu,
Here you go some tips/points on Constructors!

  • Constructor is a special method that is called automatically when an object is created,provided there is no constructor.(Default constructor with no arguments).
  • Like methods construcotrs can also have arguments,
    but it must not specify a retun type.
  • Constructor has same name as class name.
  • Constructors are not inherited.But you can call super class constructor from subclass using "super",if so it must be the first statement.
  • In the same class ,one constructor can invoke another using "this",",if so it must be the first statement.

  • Hope this helps.
I agree. Here's the link:
subject: constructor.
It's not a secret anymore!