These two statements do two things:
1)It says that the variable number and speed are integers and color is a string variable.
2)It also allocates storage for these variables.
This approach has two disadvantages:
If the program needs to keep track of various cars records. There will be more declarations that would be needed for each car, for example.
This approach can become very cumbersome.
The other drawback is that this approach completely ignores the fact that the three variables number,speed and color, are related and are a data associated with a single car.
In order to address these to drawbacks java use a class to create new types. For example to define a type that represents a car, we need storage space for two integers and a string. this is defined as follows:
A variable can be declared as of type car as follows:
The car variables of this class(number,speed and color) can be accessed using the dot(.) operator.
Creating an Object
The allocaton of memory of the reference type does not happen when the reference types are declared, as was the case of the primitive types, Simple diclaration of Non-primitive types does not allocate meomory space for the object.
In fact, a variable that is declared with a class type is not the data itself, but it is a
reference to the data, The actual storage is allocated to the object as follows.
The first statement just allocates enough space for the reference. The second statement allocates the space, called an Object, for the two integers and a string. After these two statements are executed, the contents of the Car can be accessed through c.
Example using Object.
Let us now write a example that creates an object of the class Car and display the
System.out.println("Car Number = " + number);
System.out.println("Car Speed = " + speed);
public class Object_Car
public static void main(String args)
Car Number = 401
Car Speed = 90
Car Number = 402
Car Speed = 80
Do you have an Information? Add a comment with you link!
Thanks! Your feedback helps us to improve 9lessons.info