Pet and PetMaster

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.

  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


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


Figure 7 Create a class


Figure 8 Create class Pet

4. Program Pet class. In Pet, we defined 4 variables which are:
float       weight;
String      color;
float       height;
int         age;

petcodeFigure 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 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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s