public class Bicycle {
private int cadence;
private int gear;
private int speed;
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
when you write gear = startGear; what does this actually do? does it temporary set the value of gear as whatever your input is for the time-being, then it resets back to zero? Is this called instance of a variable?
And can som开发者_运维知识库eone explain to me what exactly is an "instance of an object"? is there one in here? I thought an instance of an object is when someone writes Bicycle bike1 = new Bicycle(); and bike1 is an instance of an object. Sorry I am a total noob.
public Bicycle(int startCadence, int startSpeed, int startGear) ;
This is constructor for class Bicycle
that takes three arguments which are all of type int
. Constructor should bear the same name that of the class.
when you write gear = startGear; what does this actually do?
To such copy of variables, you are actually assigning the value of passed argument to it.
What exactly is an "instance of an object"?
There is nothing called instance of an object. You have instance for a class. And each instance has it's own class member variables. Infact, instance and object are synonyms and are often interchangeably used.
Keep the descriptive part apart and understand this diagram -
- This is the basic structure of class
Bicycle
- - Bicycle bike1 = new Bicycle(10, 4, 75) ;
When said new Bicycle(10, 4 75);
, Bicycle
class is instantiated. By instantiation means -
- Allocating memory for class members;
- Calling the class constructor, by default.
The operator new
returns the address of where the object residing on heap. So, in our case bike1
is pointing to such memory location.
(10,4,75)
are passed as parameters to the constructor and since you are doing the necessary assignment operations in the constructor, 10, 4, 75 are assigned to cadence, gear, speed
respectively.
To keep short, a copy of class variables is obtained when a class is instantiated.
So a Bicycle is an object. As such it is responsible for everything there is to know about a bicycle. So it must remember information about itself, so that at a later point in time if you ask the bicycle about itself, it can tell you info.
This code is a constructor, it initializes the Bicycle object.
So what we are doing is telling this bicycle your gear is 'startGear' some value passed into the constructor. The Bicycle saves that value in a field, so that it can reference it later.
精彩评论