File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructor.

 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remove the return type "void". Cunstructors don't have return types.
 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot, Uvnik!
I didn't notice that it is not a constructor.
Thanks again.
Mike
 
Nirmala
Ranch Hand
Posts: 93
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic