The moment a person forms a theory, his imagination sees in every object only the traits which favor that theory. [Thomas Jefferson]
In life we refer to a bicycle, dog, or car as "objects". In programming, we can create objects too. Objects can refer to concrete ideas like a particle or to more abstract ideas like a back account. The word class refers to the definition or "blueprint" of an object. The terms object and class often refer to the class.
Here's how to set up a class to define a new object:
Let's add two fields to our Bicycle class.
Now that our bike knows where it is, we need to give it the ability to do something. Let's add two methods to our object a method for drawing our bike and one for moving it.
A constructor is a special type of method that is called during the creation of an object. Notice that it does not have a return type. In the constructor, we take care of setting up the object by initializing the values of variables. We can overload constructors too. They are just functions. We might overload the constructor to provide two different ways of creating a bicycle - one where the position is set to (0,25), and one which allows you to decide.
An example of a constructor, and overloaded constructor:
Did you notice our use of this? this is a keyword that allows an object to refer to itself. It is sort of like saying "me". In our example, we use this to make a distinction between the object's xPos and yPos from the constructor's parameters. this allows the program to know to which one we refer. If we didn't do make this distinction, we would get an error because you can't have two variables in the same scope with the same name.
When we create an object, we create a reference variable.The reference variable points to the address of the object in memory. When we use the new keyword a reference to the object is created. The new keyword calls the constructor and returns the address of the new object in memory.
This newly create object is called an instance.
Bicycle myBike = new Bicycle();