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

createjavaproject1

Figure 1 Create Java Project I

2016-10-31-2-35-47-pm

Figure 2 Create Java Project II

createjavaproject3

Figure 3 New Java Project in Java Settings

2. Create a package com.java4kids.pet

createjavapackage1

Figure 4 create a java package I

createjavapackage2

Figure 5 Create Java Package II

createjavapackage3

Figure 6 Java Package

3. Create class: Pet in the package of com.java4kids.pet

createjavaclass

Figure 7 Create a class

2016-10-31-2-38-44-pm

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:

petmasterclass

Figure 11 create class PetMaster Code

petmastercode

Figure 12 class PetMaster Code

6. Finish coding, find PetMaster.java in Package Explorer, right click it. Choose Run As –> Java Application

packagestructure

Figure 13 class structure

runapp

Figure 14 run application

7. You can find the output in Console:

console

Figure 15 output in console

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s