Simple Java questions from beginner (class/object)
Hi all,
I am trying to learn java and I am a complete beginner but I keep confusing myself, think I have read too much too soon.
Basically I have this bit of code:
Dog hound = new Dog();
hound.moveLeft(3);
I am right in saying here that:
Dog = Class
hound = Variable (that stores the new object)
Dog() = Create's a new instance of the class to be stored under Hound
hound.moveLeft = Message Send to tell the object referenced by the variable hound to move left.
I am confusing myself big time here and my study books don't go any further on this.
This is pretty much all correct. Dog() itself doesn't create a new instance, its the new keyword that does so. Dog() is the datatype and constructor signature it will use (default in this example).
I don't like the terminology for the message on hound.moveLeft (message isn't quite what I would interpret of this). What would be probably better for an explanation is that moveLeft is invoked on the instance of Dog "hound", and given the value of 3. Invoke makes more sense than message, and it sounds more awesome.
I just used the moveLeft as an example and I agree with you there.
So basically, when we want to create a new variable to store a class into we do it like this:
Class Name | Variable Name | = CLASSNAME()
ie.
If I wanted to create a new variable called puppy to reference the Class Dog as an object:
Dog puppy = dog();
Or if our class was called Animal:
Animal puppy = animal();
So it is essentialy saying left to right:
[In the class Animal, create a variable called puppy] = [store class animal as a new object to variable puppy (default datatype)]
Is this correct?
I am just a little confused why we just don't say "puppy = animal ()" but hopefully if the above statement is true I'll understand better.
Not unless the functions dog/animal are declared, in scope of what is calling this code, and return the type Dog or Animal. You require the new keyword to construct a new object.
So using this:
PHP Code:
class Test { public static void main(String[] argv) { Dog puppy = dog(); } }
Would require the following in class Test:
PHP Code:
public Dog dog() { return new Dog(); // or get Dog from somewhere. }