We use a Pet and PetMaster class to explain Class and Object. You will also find property and method define. All codes are composed in Eclipse Helios Service Release 1.
- Creat a project Java4Kids
Figure 1 Create Java Project I
Figure 2 Create Java Project II
Figure 3 New Java Project in Java Settings
2. Create a package com.java4kids.pet
Figure 4 create a java package I
Figure 5 Create Java Package II
Figure 6 Java Package
3. Create class: Pet in the package of com.java4kids.pet
Figure 7 Create a class
Figure 8 Create class Pet
4. Program Pet class. In Pet, we defined 4 variables which are:
Figure 9 class Pet code
We also defined 4 methods which are:
The method sleep() is to say Good Night to PetMaster, please pay attention to that void means nothing return;
The method eat() is to tell PetMaster that Pet is hungry, need some food.
The method say() will “say” (print) the word or a phrase that we provide. We’ll pass this word to the method say() as a method argument. The method will build a phrase using this argument and will return it back to the calling program.
The method run() will display how far the pet is going to run. Speed and hour will be passed to run() as method argument. The method will return distance by speed * hour as a String back to the calling program.
5. Create class PetMaster:
Figure 11 create class PetMaster Code
Figure 12 class PetMaster Code
6. Finish coding, find PetMaster.java in Package Explorer, right click it. Choose Run As –> Java Application
Figure 13 class structure
Figure 14 run application
7. You can find the output in Console:
Figure 15 output in console