| Author |
Passing an arguament to a method and defining type
|
Matt Player
Greenhorn
Joined: Jan 11, 2009
Posts: 11
|
|
Hi there, probably easier to give code than to explain so:
and when I try to compile this I get the error:
DogTestDrive.java:6: <identifier> expected
void bark(nob) {
^
DogTestDrive.java:26: ')' expected
}
^
2 errors
Powerbook:~/javaeg matt$ javac DogTestDrive.java
DogTestDrive.java:6: <identifier> expected
void bark(nob) {
^
DogTestDrive.java:26: ')' expected
}
^
2 errors
Now it seems to be telling me that I need to identify my variable "nob" (or number of barks... of course!) but I have already declared as a variable at the top.
Please tell me why this no work??
Cheers
Matt
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 10040
|
|
you have declared nob as an instance variable for the class. That means that each and every 'Dog' object will have an integer called 'nob'.
Then you declare (create) a method. You have to explicitly list out what kind of variables you are passing into each method. So, assuming you want this to be an 'int' , you need to declare your method as
void bark (int nob)
Note then that the 'nob' variable used inside the method is DIFFERENT than the 'nob' defined for the class. They are distinct and separate.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Matt Player
Greenhorn
Joined: Jan 11, 2009
Posts: 11
|
|
you have declared nob as an instance variable for the class. That means that each and every 'Dog' object will have an integer called 'nob'.
Can I not reference this within the method then?
|
 |
Balu Sadhasivam
Ranch Hand
Joined: Jan 01, 2009
Posts: 874
|
|
You can very well use it using "this" keyword (this.nob). "this" refers to the current instance which invoked the instance method (void bark).
Fred meant that since you have passed nob as parameter , it acts as a local variable and is distinct and separate from the instance variable "nob'
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 10040
|
|
you can, but you have to let java know which one you mean. And that requires you to know which one you mean.
if you want to use the member variable, then why are you passing it into the method? In other words, if you changed your method to this:
inside the method, you could refer to numberOfBarks (which is local to the method), or you could refer to nob, which is part of the class.
My guess is that you want to use numberOfBarks, because otherwise you'll permanently change the nob value inside your method.
|
 |
 |
|
|
subject: Passing an arguament to a method and defining type
|
|
|