Monday, 6 August 2007

Java Language Fundamentals (Part 9)

Objects and Classes - cont

Now, you can create a new type by basing it on your class. The variables within the class and the final constant are called members and can be referenced by a variable which has been declared on the new type.
For example:

TheCar myCar;

Using this declaration, you can reference the variables by using dot (.) notation. Again, using the car example:

myCar.topSpeed = 127;
myCar.lowSpeed = 25;

The myCar variable which is based on the TheCar class is declared not on the data itself, but rather a reference to the data. You can (if you like) think of the variable myCar as a pointer to the class TheCar. This is because the declaration of myCar doesn’t actually allocate memory space for that object.

Before you can actually use this reference variable (myCar) you have to instantiate it using the keyword new. This will allocate space for the three integers used to form TheCar. This reference (myCar) now becomes an object.

To finish the example:
class TheCar{
int topSpeed;
int lowSpeed;
final int MAX_SPEED = 200;
}
public class OurCar{
public static void main(String args[]){
TheCar myCar;
myCar = new TheCar();
myCar.topSpeed = 127;
myCar.lowSpeed = 25;
System.out.println("top speed = " + myCar.topSpeed);
System.out.println("low speed = " + myCar.lowSpeed);
System.out.println("max speed = " + myCar.MAX_SPEED);
}
}

Exercise 2 – 1 using a class variable
· Use the above material to create an application called BigPet which will print 5 different attributes (features) of the concept of a pet (number of legs, tail, weight, name, colour) Use a class called AllPets to hold the member variables. Then use println to send the string “My pets name is Binky and he has 8 legs. He is black and weighs 0.89 kg”

No comments:

Post a Comment