wood burning stoves 2.0*
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
Author

constructor.

Anonymous
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");
m.go(m.s);
System.out.println("m.s is "+m.s);
}

void go(String s) {
System.out.println(s);
}
}
i must missing something. please help. Thanks.
Mike
Uvnik Gupta
Ranch Hand

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

Joined: Nov 22, 2008
Posts: 18944
Thanks a lot, Uvnik!
I didn't notice that it is not a constructor.
Thanks again.
Mike
Nirmala
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.
    Nirmala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: constructor.
 
Similar Threads
Please help to clear this
thread doubt
Constructors/Strings HELP
Inheritance Doubt?
doubt on thread