Originally posted by �int��:
[QB]
means this variable will not be accessible outside this class right? The Private part I mean...
private means that any code that calls an instance of Dog can't call this particular member. You can use the variable "name" anywhere inside the Dog class. But if you were to write some code that did
public Dog(String name) {
this.name = name;
}
This is the Method, I get that...
Where dose "this" come from?
this is a variable which refers to the current object itself. Within a class, it basically means "myself." So when you type this.name, that means "the name variable within myself." The reason for using this there is because the member variable is named this, but so is the parameter for the constructor. If you don't use "this" in this case, then it doesn't do anything, because the parameter takes precedence. You use "this" here to specify that the member variable should be assigned the value of the parameter.
When called it will basically say
name = Fido; ?
I mean once the variable is filled it will be Fido?
After this statement, the member variable "name" will have the same value as the parameter passed in.
So what about this?
cobi.bark();
dog2.bark();
Or when dog2.bark(); is called is that where Fido is assigned? What about cobi.bark();? I am so confused over this little blurb of code. /me slams head into sharp pencil.
The name gets assigned in the constructor. A constructor is a special method that's used to build objects. Unless you call a constructor, the object will be null. The bark() method just displays a line of text. Despite the fact that they both show the same output, they're actually being run on different objects. Try running the code
public String getName() {
return name;
}
gets the name abviously, but "return name;" what dose this do? Same as print or println? Or maybe pass it on?
That just passes back the value of "name". That's called an accessor method, and it's how you let other parts of the program access the data of a particular object. All it does is give a String back...so you could do something like
public void bark() {
System.out.println("woof!");
}
Obviously prints out "woof!" but what about the rest of the properties of the dog like the name.
All that does is display a line. You could change it to something like:
public void bark() {
System.out.println("My name is " + name);
}
And you'll see that each dog will output a different name. I wrote a short example above.