Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructor problem

 
Samarth Barthwal
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following code when I take the name of the reference same while calling both the constructors i get an error stating "c is already defined in main(java.lang.String[])".But when I change the name of one of the references I get no errors.Why is it so?


 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A type (cont) followed by a variable name (c) is the syntax for declaring a variable. So when you say "cont c" a second time, Java thinks you're trying to declare a second variable with the same name as the first.

If you want to use the same c after declaring it, just use the variable name without the type...

cont c = new cont(); //declaration (and assignment)
c = new cont(6); //reassignment

If you want a different variable, then provide the type for the new variable...

cont c = new cont();
cont d = new cont(6);
 
Samarth Barthwal
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am still confused
What I have learned is that on writing:

we create a memory space for an object of cont type,and when we write:

we create a reference to the memory allocated to the object.
Then when we write:

What is actually happening and why?
[ March 20, 2006: Message edited by: Samarth Barthwal ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When a variable is first declared, its type needs to be specified. But any time after the declaration, the variable name is used by itself (without the type). For example...

cont c; //variable declaration
c = new cont(); //assignment

Note that in the above example, the second line would not be valid unless we had previously declared 'c' as a variable of type cont.

Declaration and assignment can be combined in the same line...

cont c = new cont(); //declaration AND assignment
 
Samarth Barthwal
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Marc for the help.
[ March 21, 2006: Message edited by: Samarth Barthwal ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic