Report

Java Programming For Kids

To view this page ensure that Adobe Flash Player version 9.0.124 or greater is installed.

Get Adobe Flash player
Please login or register to make a comment!

Java TM Programming for Kids, Parents and GrandParents Yakov Fain Java Programming for Kids, Parents and Grandparents iii Java Programming for Kids, Parents and Grandparents by Yakov Fain Copyright © 2004 Smart Data Processing, Inc. 14 Molly Pitcher Dr. Manalapan, New Jersey, 07726, USA All rights reserved.

No part of this book may be reproduced, in any form or by any, without permission in writing from the publisher. Cover design and illustrations: Yuri Fain Adult technical editor: Yuri Goncharov Kid technical editor: David Fain May 2004: First Electronic Edition The information in this book is distributed without warranty. Neither the author nor the publisher shall have any liability to any person or entitle to any liability, loss or damage to be caused directly or indirectly by instructions contained in this book or by the computer software or hardware products described herein.

Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. Windows 98, Windows NT, Windows 2000 and Windows XP are trademarks of Microsoft Corporation.

All other product names and company names are the property of their respective owners. The publisher offers discount on this book when ordered in bulk ... more. less.

quantities. For more information, send an e-mail at books@smartdataprocessing.com .<br><br> ISBN: 0-9718439-5-3 Table of Contents PREFACE ...............................................................................................IX ACKNOWLEDGEMENTS .............................................................................XI CHAPTER 1. YOUR FIRST JAVA PROGRAM .................................................... 1 How to Install Java on Your Computer.......................................................................................<br><br> 2 Three Main Steps in Programming .............................................................................................. 6 Step 1 3 Type the Program...................................................................................................... .....<br><br> 6 Step 2 3 Compile the Program................................................................................................... ... 8 Step 3 3 Run the Program.......................................................................................................<br><br> ...... 9 Additional Reading ............................................................................................................ ..........<br><br> 10 CHAPTER 2. MOVING TO ECLIPSE .............................................................. 11 Installing Eclipse ............................................................................................................<br><br> .............. 11 Getting Started with Eclipse................................................................................................... .....<br><br> 13 Creating Programs in Eclipse .................................................................................................. ... 15 Running HelloWorld in Eclipse...............................................................................................<br><br> 16 How HelloWorld Works? ........................................................................................................ 17 Additional Reading ............................................................................................................<br><br> .......... 20 Practice....................................................................................................................... ...................<br><br> 20 Practice for Smarty Pants...................................................................................................... ...... 21 CHAPTER 3.<br><br> PET AND FISH 3 JAVA CLASSES .............................................. 22 Classes and Objects............................................................................................................ ..........<br><br> 22 Data Types .................................................................................................................... ................ 25 Creation of a Pet.............................................................................................................<br><br> ............. 28 Inheritance 3 a Fish is Also a Pet............................................................................................. ...<br><br> 33 Method Overriding ............................................................................................................. ......... 37 Additional Reading ............................................................................................................<br><br> .......... 38 Practice....................................................................................................................... ...................<br><br> 38 Practice for Smarty Pants...................................................................................................... ...... 39 Java Programming for Kids, Parents and Grandparents v CHAPTER 4.<br><br> JAVA BUILDING BLOCKS ....................................................... 40 Program Comments............................................................................................................... ......<br><br> 40 Making Decisions with if Statements........................................................................................ 41 Logical Operators.............................................................................................................. ...........<br><br> 43 The logical not here is applied to the expression in parentheses.............................................. 44 Conditional operator........................................................................................................... .........<br><br> 44 Using else if ............................................................................................................................ 44 Making Decisions With switch Statement.............................................................................. 45 How Long Variables Live?.......................................................................................................<br><br> ... 46 Special Methods: Constructors.................................................................................................. .<br><br> 47 The Keyword this ...................................................................................................................... 48 Arrays......................................................................................................................... ...................<br><br> 49 Repeating Actions with Loops................................................................................................... .. 51 Additional Reading ............................................................................................................<br><br> .......... 54 Practice....................................................................................................................... ...................<br><br> 54 Practice for Smarty Pants...................................................................................................... ...... 54 CHAPTER 5.<br><br> A GRAPHICAL CALCULATOR ................................................... 55 AWT and Swing ................................................................................................................. ..........<br><br> 55 Packages and Import Statements................................................................................................ 55 Major Swing Elements........................................................................................................... ......<br><br> 56 Layout Managers................................................................................................................ .......... 59 Flow Layout....................................................................................................................<br><br> ........... 59 Grid Layout.................................................................................................................... ............<br><br> 60 Border Layout ................................................................................................................. ........... 62 Combining Layout Managers.....................................................................................................<br><br> 62 Box Layout..................................................................................................................... ............ 65 Grid Bag Layout................................................................................................................<br><br> ......... 66 Card Layout.................................................................................................................... ............<br><br> 68 Can I Create Windows Without Using Layouts? ....................................................................... 68 Window Components..............................................................................................................<br><br> ..... 68 Additional Reading ............................................................................................................ ..........<br><br> 72 Practice....................................................................................................................... ................... 72 Practice for Smarty Pants......................................................................................................<br><br> ...... 73 CHAPTER 6. WINDOW EVENTS .................................................................<br><br> 74 Interfaces..................................................................................................................... .................. 75 Action Listener ...............................................................................................................<br><br> .............. 77 Registering Components with ActionListeneter ............................................................. 78 What 9s the Source of an Event?<br><br> ................................................................................................ . 79 How to Pass Data Between Classes.............................................................................................<br><br> 8 1 Finishing Calculator........................................................................................................... .......... 83 Some Other Event Listeners.....................................................................................................<br><br> .. 89 How to Use Adapters............................................................................................................ ........<br><br> 90 Additional Reading ............................................................................................................ .......... 91 Practice.......................................................................................................................<br><br> ................... 91 Practice for Smarty Pants...................................................................................................... ......<br><br> 91 CHAPTER 7. THE TIC-TAC-TOE APPLET ..................................................... 92 Learning HTML in 15 Minutes...................................................................................................<br><br> 93 Writing Applets Using AWT...................................................................................................... . 96 How to Write AWT Applets.......................................................................................................<br><br> . 97 Writing a Tic-Tac-Toe Game..................................................................................................... .<br><br> 99 The Strategy................................................................................................................... ............ 99 The Code.......................................................................................................................<br><br> ........... 100 Additional Reading ............................................................................................................ ........<br><br> 110 Practice....................................................................................................................... ................. 110 Practice for Smarty Pants......................................................................................................<br><br> .... 111 CHAPTER 8. PROGRAM ERRORS - EXCEPTIONS ........................................<br><br> 112 Reading the Stack Trace........................................................................................................ .... 113 Genealogical Tree of Exceptions...............................................................................................<br><br> 114 The keyword throws ................................................................................................................ 117 The Keyword finally .......................................................................................................... 118 The Keyword throw ...............................................................................................................<br><br> 119 Creating New Exceptions........................................................................................................ ... 121 Additional Reading ............................................................................................................<br><br> ........ 123 Practice....................................................................................................................... .................<br><br> 123 Java Programming for Kids, Parents and Grandparents vii Practice for Smarty Pants...................................................................................................... .... 123 CHAPTER 9.<br><br> SAVING THE GAME SCORE ................................................... 124 Byte Streams................................................................................................................... ............<br><br> 124 Buffered Streams............................................................................................................... ......... 127 Command-Line Arguments.......................................................................................................<br><br> 1 29 Reading Text Files............................................................................................................. ......... 132 Class File ...............................................................................................................................<br><br> ... 135 Additional Reading ............................................................................................................ ........<br><br> 137 Practice....................................................................................................................... ................. 137 Practice for Smarty Pants......................................................................................................<br><br> .... 138 CHAPTER 10. MORE JAVA BUILDING BLOCKS .........................................<br><br> 139 Working with Date and Time Values ....................................................................................... 139 Method Overloading............................................................................................................. .....<br><br> 140 Reading Keyboard Input......................................................................................................... .. 143 More on Java Packages..........................................................................................................<br><br> .... 145 Access Levels.................................................................................................................. .............<br><br> 148 Getting Back to Arrays........................................................................................................ ..... 151 Class ArrayList ......................................................................................................................<br><br> 154 Additional Reading ............................................................................................................ ........ 158 Practice.......................................................................................................................<br><br> ................. 158 Practice for Smarty Pants...................................................................................................... ....<br><br> 159 CHAPTER 11. BACK TO GRAPHICS 3 THE PING PONG GAME ..................... 160 The Strategy...................................................................................................................<br><br> ............. 160 The Code....................................................................................................................... ..............<br><br> 161 Java Threads Basics............................................................................................................ ....... 169 Finishing Ping Pong Game ......................................................................................................<br><br> .. 175 What to Read Next on Game Programming............................................................................ 185 Additional Reading ............................................................................................................<br><br> ........ 186 Practice....................................................................................................................... .................<br><br> 186 Practice for Smarty Pants...................................................................................................... .... 186 APPENDIX A.<br><br> JAVA ARCHIVES - JARS ...................................................... 188 Additional Reading ............................................................................................................ ........<br><br> 189 APPENDIX B. ECLIPSE TIPS .................................................................... 190 Eclipse Debugger...............................................................................................................<br><br> ......... 191 APPENDIX C. HOW TO PUBLISH A WEB PAGE .........................................<br><br> 194 Additional Reading ............................................................................................................ ........ 197 Practice.......................................................................................................................<br><br> ................. 197 INDEX .................................................................................................... 198 Java Programming for Kids, Parents and Grandparents ix Preface One day my son Davey-steamboat showed up in my office with my rated cR d Java tutorial in his hands.<br><br> He asked me to teach him programming so he could create computer games. At that time I 9ve already written a couple of books on Java and taught multiple classes about computer programming, but all of this was for grownups! A search on Amazon could not offer anything but books for dummies, but Davey is not a dummy!<br><br> After spending hours on Google I found either some poor attempts to create Java courses for kids, or some reader-rabbit-style books. Guess what? I decided to write one.<br><br> To help me understand the mentality of the little people, I decided to ask Davey to become my first kid student. This book will be useful for the following groups of people " Kids from 11 to 18 years old " School computer teachers " Parents who want to teach their kids programming " Complete beginners in programming (your age does not matter) Even though I use a simple language while explaining programming, I promise to treat my readers with respect - I 9m not going to write something like cDear friend! You are about to begin a new and exciting journey& d.<br><br> Yeah, right! Just get to the point! First chapters of the book will end with simple game-like programs with detailed instructions on how to make them work.<br><br> Also we are going to create a calculator that looks and works similarly to the one that you have in your computer. In the second part of the book we 9ll create together game programs Tic-Tac-Toe and Ping- Pong. You 9ll need to get used to the slang of professional programmers, and all important words will be printed in this font.<br><br> Java language elements and programs will be shown in a different font, for example String . This book does not cover each and every element of the Java language, otherwise it would be too fat and boring. But at the end of each chapter there is a section Additional Reading wit links to Web sites with more detailed explanations of the subject.<br><br> You 9ll also find assignments at the end of each chapter. Every reader has to complete assignments given in the section Practice . If these assignments are too easy for you, I challenge you to do assignments from the section Practice for Smarty Pants .<br><br> Actually, if you are reading this book, you are a smart person and should try to complete all the assignments. To get the most out of this book, read it from the beginning to the end. Do not move on until you understand the chapter you are reading now.<br><br> Teenagers, parents and grandparents should be able to master this book without asking for help, but younger kids should read this book with an adult. Java Programming for Kids, Parents and Grandparents xi Acknowledgements Thank you all architects and developers who worked for free on Eclipse 3 one of the best available Integrated Development Environment for Java. Special thanks to New Jersey Transit bus drivers for the smooth ride 3 a half of this book has been written while commuting to work on the bus #139.<br><br> Thanks to a lovely lady and my wife Natasha for successfully running a business called family. Special thanks to Yuri Goncharov - an expert Java programmer from Toronto, Canada. He reviewed the book, tested every code example, and provided a valuable feedback to make this book a little better.<br><br> Chapter 1. Your First Java Program P eople talk to each other using different languages. Similarly, they write computer programs like games, calculators, text editors using different programming languages.<br><br> Without programs, your computer would be useless, and its screen would be always black. Computer parts are called hardware , and programs are known as software . The most popular computer languages are Visual Basic, C++, and Java.<br><br> What makes the Java language different from many others? First of all, the same Java program can run (work) on different computers like PC, Apple and others without changes. As a matter of fact, Java programs do not even know where they run, because they run inside of a special software shell called Java Virtual Machine (JVM).<br><br> If, for example, your Java program needs to print some messages, it asks JVM to do this, and JVM know how to deal with your printer. Second, Java makes it easy to translate your programs (screens, menus and messages) to different human languages. Third, Java allows you to create program elements ( classes ) that represent objects from the real world.<br><br> For example, you can create a Java class called Car and set attributes of this class like doors, wheels, similarly to what the real cars have. After that, based on this class you can create another class, for example Ford , which will have all the features of the class Car plus something that only Fords have. Fourth, Java is more powerful than many other languages.<br><br> Fifth, Java is free! You can find everything for creating your Java programs on the Internet without paying a penny! How to Install Java on Your Computer To start programming in Java you need to download a special software from the Web site of the company called Sun Microsystems, that created this language.<br><br> The full name of this software is Java 2 Software Development Kit (J2SDK). At the time of this writing its latest version 1.5.0 could be downloaded from this Web site: http://java.sun.com/j2se Select release J2SE 1.5.0 or the newer one, and on the next Web page under the title Downloads click on the link to this release. Then click on the word Download under the title SDK.<br><br> Accept the license agreement and select Windows Offline Installation (unless you have a Mac, Linux or Solaris computer). Press the button Save on the next screen and select the folder on your hard disk where you 9d like to save the Java installation file. The file download will start.<br><br> After the download ends, start the installation process 3 just double-click on the file that you 9ve downloaded, and this will install J2SDK on your disk. For example, on Windows computer it will create a folder like this one: c:\Program Files\java\j2sdk1.5.0 , where c: is the name of your hard disk. Java Programming for Kids, Parents and Grandparents 3 If you do not have enough room on your c: drive, select a different one, otherwise, just keep pressing the buttons Next , Install and Finish on the windows that will be popping up on your screen.<br><br> In several minutes the installation of Java on your computer will be complete. In the next step of installation, you need to define two system variables . For example, in Windows click on the button Start , and get to the Control Panel (it might be hidden behind the menu Settings ), and click on the icon System .<br><br> Select there a tab Advanced , and click on the button Environment Variables . On the next page you can see how this screen looks like on my Windows XP notebook. Th bles that already exist in your system.<br><br> e next window will show all system varia Java Programming for Kids, Parents and Grandparents 5 ress the lower button New and declare the variable that will exists, just add the new Java directory and a box Variable Value : P Path help Windows (or Unix) find J2SDK on your machine. Double check the name of the folder where you 9ve installed Java. If the variable Path already semicolon to the very beginning of the Also, declare the variab semicolon as its value.<br><br> T your programs. The pe your programs from the just a separator: le CLASSPATH by entering a period and a his system variable will help Java find riod means that Java has to start looking for current disk folder, and the semicolon is Now the installation of J2SDK is complete! Compile the program to translate it from Java language into M understands.<br><br> e Program hree Main Steps in Programming T To create a working Java program you need to go through the following tree steps: Write the program in Java and save it on a disk. a special byte code that JV Run the program. Step 1 3 Type th You can use any text editor to write Java programs, for example Notepad.<br><br> If you have an old Windows 98 computer, you 9ll need to set the PATH and CLASSPATH variable in a different way. Find Notep these variable at end of this file, for example: SET CLASSPATH=.; the file autoexec.bat on your c: drive, and using ad or other text editor enter the proper values for SET PATH=c:\j2sdk1.5.0\bin;%PATH% After making this change you 9ll need to restart your computer. Java Programming for Kids, Parents and Grandparents 7 First, you 9ll need to type the program and save it in a text file with a name ending in .java .<br><br> For example, if you want to write a program called HelloWorld , enter its text (we call it source code ) in m that prints on the screen the words Hello orld : I 9ll explain how th r, but at this point just trust me 3 this program will print the words Hello World in the step 3. Notepad and save it in the file named HelloWorld.java. Please do not use blanks in Java file names.<br><br> ere is the progra H W is program works a little later in this chapte public class Hel public sta Syst ello World" ); } } loWorld { tic void main(String[] args) { em.out.println( "H Step 2 3 Compile the Program ow you compile rogram. Y using the javac piler , which is a 2SDK. say you 9ve our program N need to this ou 9ll be p com part of J Let 9s saved y in the directory calle d c:\practice .<br><br> Select the menus Start , Run , and enter the word cmd to open a black command window. Just to make sure that you 9ve set the system variables PATH and CLASSPATH correctly, enter the word set and take another look at eir values. er to c:\practice and compile the The program javac is Java compiler .<br><br> You won 9t see any confirmation that your program HelloWorld has been compiled successfully. This is the case when no news is good news. Type a command dir and it 9ll show you all the files that exist in your folder.<br><br> You should see there a new file named HelloWorld.class . This proves that your program has been successfully compiled. Your original file HelloWorld.java is also there, and you can modify this file later to print Hello Mom or something else.<br><br> th Change the current fold rogram: p cd \practice javac HelloWorld.java You do not have to name the folder practice 3 give it any name you like. In Windows 98 select the cMS DOS Prompt d from the Start menu to open a command prompt window. Java Programming for Kids, Parents and Grandparents 9 If the program has syntax errors, let 9s say you forgot to type the last curly brace, Java compiler will print an error message.<br><br> Now you 9d need to fix the error, and recompile the program again. If you have several errors, you may need to repeat these actions more than once until the file HelloWorld.class is created. Step 3 3 Run the Program Now let 9s run the program.<br><br> In the same command window enter the following: java HelloWorld Have you noticed that this time you 9ve used the program java instead of javac? This program is called Java Run-time nvironment (JRE) , or you may call it JVM like I did before. E treat capital and small let named the program H Keep in mind that Java does n same, which means that if yo with a capital H and a capital helloworld or helloWorld 3 Now let 9s have some ot t s the u elloWorld W , do not try to start the program JV will complain.<br><br> fun - try to guess how to change this program. I 9ll explain how this program works in the next chapter, but still, try to guess how to change it to say hello to you pet, friend or print your address. Go through all three steps to see if the program still works after your changes : .<br><br> In the next chapter I 9ll show you how to type, compile and run your programs in a more fancy place than a text editor and a black command window. er M Additional Reading Creating your first application: http://java.sun.com/docs/books/tutorial/getStarted/c upojava/win32.html Java installation instructions for Windows: http://java.sun.com/j2se/1.5.0/install-windows.html Java Programming for Kids, Parents and Grandparents 11 Chapter 2. Moving to Eclipse P rogrammers usually work in so-called Integrated Development Environment (IDE).<br><br> You can write, compile and run programs there. IDE also has a Help thingy that describes all elements of the language, and makes it easier to find and fix errors your programs. While some IDE programs are expensive, there an excellent free IDE called Eclipse.<br><br> You can download it from in is the Web site www.eclipse.org . In this chapter I 9ll help you to download and install Eclipse IDE on your computer, create there a project called Hello World , and after this we 9ll be creating all our programs there. Make yourself comfortable in Eclipse 3 it 9s an excellent tool that many professional Java programmers use.<br><br> Installing Eclipse Open the Web page www.eclipse.org and click on the Download enu on the left (http). Click on the link Main Eclipse Download Site and select the version of Eclipse you want to download. They usually have one latest release and several stable builds .<br><br> The latest release is an officially released product. Even though stable builds may have more features, they still may have some minor problems. At the time of this writing the latest stable build is 3.0M8.<br><br> Select this build and you 9ll see the following window: m Click on the link (http) next to the word Windows, Mac, or Linux load the file with this long name that ends with .zip to any folder on your disk. Now you just have to unzip this file into your c: drive. If you already have the program WinZip installed on your computer, right-click on this file and select the WinZip on the menu and the option Extract To .<br><br> If you have room on your c: drive, press the button Extract , otherwise select another disk that has more space available. depending on your computer, and down Files with the name suffix .zip are archives, and they contain many other files inside. To unzip the file means to extract the content of this archive on the disk.<br><br> The most popular archive program is called WinZip and you can download its trial version at www.winzip.com . You 9ll need it to complete installation of Eclipse. Java Programming for Kids, Parents and Grandparents 13 Installation of Eclipse is complete!<br><br> For your convenience, create the shortcut for Eclipse. Right-click on the desktop of your computer, then press New , Shortcut , Browse , and select the file eclipse.exe in the folder c:\eclipse . To start the program, double-click on the blue icon Eclipse , and you 9ll see the first Welcome screen (this screen is changing sligtly with e ach Eclipse build): If your screen looks different, proceed to so-called Workbench , nd run ava program u can also find a nice tutorial under Development User everal files.<br><br> press the button Next on the New roject Window. Now you 9ll need to enter the name of your new My First Project : which is the working area for your Java projects. Getting Started with Eclipse In this section I 9ll show you how you can quickly create a J s in Eclipse.<br><br> Yo the menus Help , Help Contents , and Java uide . G To start working on a program you 9ll need to create a new project. A simple project like our HelloWorld will have just one file 3 HelloWorld.java .<br><br> Pretty soon we 9ll create more advanced rojects that will consist of s p To create a brand new project in Eclipse just click on the menus File , New , Project , and then P project, for example Look at the grayed out box Directory . It tells you where the files of this project will be located on the disk. Eclipse has a special folder workspace , where it keeps all files for your projects.<br><br> Later on, you 9ll create separate projects for a calculator program, a Ti -Tac- oe game, and other programs. There will be several projects in the kbench has several smaller areas called perspectives hich are different views of your projects. c T workspace folder by the end of this book.<br><br> Eclipse wor w Java Programming for Kids, Parents and Grandparents 15 you click on the little plus sign by My First Project , it 9ll expand nvironment (JRE) ystem Library which is a part of the project If for any reason you d Preferenc button B nstalled Java, for example c:\j2sdk1.5.0. Creatin Let 9s recr Java programs are classes that represent objects from real life. ou 9ll learn more about classes in the next chapter.<br><br> To create enter He methods If showing you an item Java Run-time E S o not see JRE there, click on the menus Windows , es, Java, Editor, Installed JREs, Add , and, using the rowse find the folder where you have i g Programs in Eclipse eate the HelloWorld program from Chapter 1 in Eclipse. Y a class in Eclipse select the menus File , New , Class and lloWorld in the field Name . Also, in the section Which stubs you would like to create , check off the box public static void main(String[] args) escribe our class.<br><br> After the comments you 9ll find the code of the class HelloWorld with an empty method main() . The word method means action . To run a Java class as a program, this class must have a method called main() .<br><br> To complete our program, place the cursor after the curly brace in the line with main , push the button Enter and type the following on the new line: Press the button Finish , and you 9ll see that Eclipse created for you the class HelloWorld . It placed program comments (the text between /* and */) on top - you should change them to d y public class HelloWorld { public static void main(String[] args) { } } System.out.println( "Hello World" ); To save the program on disk and compile it, just press at the same time two buttons on your keyboard: Ctrl-S . If you did not make ny syntax errors, you won 9t see any messages 3 the program is ickly find nes by double-clicking on the tive .<br><br> Let 9s put the curly brace program is a one-class project. But pretty soon you rojects will have several Java classes. That 9s why before running elect the menu Run , then Run& (make sure that Java Application selected in the top left corner), and enter the names of the project and the main class: a compiled.<br><br> But let 9s make an error on purpose to see what 9s going to happen. Erase the last curly brace and hit Ctrl-S again. Eclipse will display the Unmatched Brace error in the tasks perspective, and also it will place a red mark at the line that has a problem.<br><br> As your projects become larger, they 9ll have several files and ompiler may generate more than one error. You can qu c (not fix though) the problematic li ror message in the tasks perspec er back and hit Ctrl-S again 3 voila, the error message is gone! Running HelloWorld in Eclipse Our simple p the project for the first time, you need to tell Eclipse which class in this project is the main one.<br><br> S is Java Programming for Kids, Parents and Grandparents 17 Now press the bu int the words Hello W nsole view the same way as it did in Chapter 1. ow you can run his project by selecting the menus Run , Run Last aunched or by pressing the buttons Ctrl-F11 on the keyboard. How HelloWorld Works?<br><br> Let 9s start learning what 9s actually happening in the program HelloWorld . The class HelloWorld has only one method main (), which is an entry point of a Java application (program). You can tell that main is a method, because it has parentheses after the word main .<br><br> Methods can call (use) other methods, for example our method main() calls the method println() to display the text Hello World on the screen. Each method starts with a declaration line called a method signature : tton Run , to start the the program. It will pr orld in the co N t L public static void main(String[] args) lowing: \x2 Who can access the method - public.<br><br> The keyword public m essed by any o \x2 Instructions on how to use it - static. The keyword static means that you don 9t have to create an instance (a copy ) of HelloWorld object in memory to use this method. We 9ll talk about class instances more in the next chapter.<br><br> \x2 Does the method return any data? The keyword void means that the method main() doesn 9t return any data to the calling program, which is Eclipse in this case. But if for example, a method had to perform some calculations, it could have returned a resulting number to its caller.<br><br> \x2 The name of the method is main. \x2 The list of arguments 3 some data that could be given to the method - String[] args . In the method main() the String[] args means that this method can receive an array of Strings that represent text data.<br><br> The values that are being passed to a method are called arguments . I said before, you can have a program that consists of several asses, but one of them has the method main() . Java class usually have several methods.<br><br> For example, a class Game can have the methods startGame(), stopGame(), readScore() , and so on. The body of our method main()ha s only one line : This method signature tells us the fol eans that the method main() could be acc ther Java class or JVM itself. As cl System.out.println( "Hello World" ); Every command or a method call must end with a semicolon ;.<br><br> The method println() knows how to print data on the system console (command window). Java 9s method names are always followed by parentheses. If you see a method with empty parentheses, this means that this method does not have any arguments.<br><br> The System.out means that the variable out is defined inside the class System that comes with Java. How are you supposed to know that there 9s something called out in the class System ? Eclipse will help you with this.<br><br> After you type the word System and a dot, Eclipse will show you everything that is available in this Java Programming for Kids, Parents and Grandparents 19 lass. At any time you can also put a cursor after the dot and press c Ctrl-Space to bring up a help box similar to this one: The out.println() tells us that there is an object represented by mething called out d has a method etween a class and a method name eans that this method exists inside this class. Say you have a lass PingPongGame that has a method saveScore() .<br><br> This is how call this method for Dave who won three games: a variable out and this cso called println() . The dot b m c you can Pi Again, the data between parentheses are called arguments or pa ameters . These parameters are given to a method for some kind of processing, for example saving data on the disk.<br><br> The method saveScore() has two arguments 3a text string cDave d, and the number 3. ngPongGame.saveScore( "Dave" , 3); r Eclipse will add fun to writing Java programs. Appendix B has some useful tips and tricks that will speed up your Java programming in this excellent IDE.<br><br> Additional Reading Eclipse Web Page: http://www.eclipse.org Practice Change the class HelloWorld to print your address using several calls to println() . Java Programming for Kids, Parents and Grandparents 21 Practice for Smarty Pants Change the class HelloWorld to print the word Hello like this: 3. Pet and Fish 3 Java Classes have different preferences em agree that it 9s better to in a so-called object-oriented style.<br><br> This means that good mers start with deciding which objects have to be lasses an Objects ideoGame . This class may ave several methods, which can tell what objects of this class can e, stop it, save the score, and so on. This class ave some attributes or properties: price, screen color, ntrols and others.<br><br> Chapter J ava programs consist of classes that represent objects from the real world. Even though people may s to how to write programs, most of th a do it program included in the program and which Java classes will represent them. Only after this part is done, they start writing Java code.<br><br> d C Let 9s create and discuss a class named V h do : start the gam also may h number of remote co Classes in Java may have methods and attributes . cribe the class. Methods define actions that a class can perform.<br><br> Attributes des Java Programming for Kids, Parents and Grandparents 23 In Java language this class may look like this: screens of different size nd color, all of them perform similar actions, and all of them cost o attributes cartridgeType and screenWidth and two methods 3 startGame() and stopGame() . But these methods can 9t perform class VideoGame { String color; int price; void start () { } void stop () { } void saveScore(String playerName, int score ) { } } Our class VideoGame should be similar to other classes that represent video games 3 all of them have a money. We can be more specific and create another Java class called GameBoyAdvance .<br><br> It also belongs to the family of video games, but has some properties that are specific to the model GameBoy Advance, for example a cartridge type. In this example the class GameBoyAdvance defines tw class GameBoyAdvance { 3 String cartridgeType; int screenWidth; void startGame() { } void stopGame() { } } any a curly bra relates to its instance in ess of building actual games based on this e process of creating ctions just yet, because they have no Java code between the ces. A factory description of the GameBoy Advance relates to an actual me the same way as a Java class In a i the new meaning of the word object .<br><br> The ga memory. The proc description in the game factory is similar to th instan GameBoy . ces of objects in Java In many cases, a program can use a Java class only after its nstance ha i s been created.<br><br> Vendors also create thousands of game e description. Even though these copies they may have different values in their d so s, a program may create multiple instances of the GameBoyAdvance objects. copies based on the sam present the same class, re attributes - some of them are blue, while others are silver, an on.<br><br> In other word dd tion to the word class , you 9ll have to get used to phrase cto create an instance of an object d means to create a copy of this object in the computer 9s memory rd ng to the definition of its class. acco i Java Programming for Kids, Parents and Grandparents 25 a a variables represent attributes of a class, method arguments r ethod for a short-time storage of o a. Variables have to be declared first, and only after this declare v bles x of some numeric data type like integer or o Data Types J v o could be used inside the m e dat s m is done you can use them.<br><br> Remember equations like y=x+2? In Java you 9d need to aria and y the d uble : in x; t in h o lines show how you can assign a value to these a , even: = = +2; Java you are also allowed to change the value of a variable in a omewhat unusual way. The following two lines change the value the variable y from five to six: t y; e next tw T v riables.<br><br> If your program assigns the value of five to the variable the variable y will be equal to s x x 5; y x In s of i y+ nt y=5; +; Despite the two plus signs, JVM is still going to increment the value of the variable y by one . After the next code fragment the value of the variable myScore is lso six: a int myScore=5; myScore=myScore+1; You can also use multiplication, division and subtraction the same ay. Look at the following piece of code: w i nt myScore=10; myScore--; myScore=myScore*2; myScore=myScore/3; System.out.println( "My score is " + myScore); What this code prints?<br><br> Eclipse has a cool feature called a scrapbook that allows quickly test any code snippet (like the one above) without even creating a class. Select menus File , New , Scrapbook Page and type the word Test as the name of your scrapbook file. Now enter these five lines that manipulate with myScore in the scrap book, highlight them, and click on the little looking glass on the toolbar.<br><br> To sult of the score calculations, just click on the o ole tab at the bottom of the screen: re is d and the value of the ariable myScore , which was six. Creation of a String from pieces called concatenation . Even though myScore is a number, Java gh to convert this variable into a String , and then t text My Score is .<br><br> ways of changing the values of the variables: ore=myScore*2; is the same as myScore*=2; yScore=myScore+2; is the same as myScore+=2; here are eight simple, or primitive data types in Java, and you have t data that s ns ee the re c My score is 6 In this example the argument of the method println() was glued rom two pieces 3 the text cMy sco f v is is smart enou a tach it to the Look at some other mySc m myScore=myScore-2; is the same as myScore-=2; myScore=myScore/2; is the same as myScore/=2; T o decide which ones to use depending on the type and size of you are planning to store in your variables: Java Programming for Kids, Parents and Grandparents 27 One logical data type called boolean that allows only two You can assign an initial value to a variable during its declaration n ble initialization : Four data types for storing integer values 3 byte , short , int , and long. Two data types for values with a decimal point 3 float and double. One data type for storing a single character 3 char.<br><br> values: true or false . d this is called varia a char grade = 'A' ; in t chairs = 12; bo = false ; olean playSound do 3863494965745.78; uble nationalIncome = 2 fl oat gamePrice = 12.50f; lo last two lines f means float and l means long. s boolean a les, and a special code 8\u0000 9 to a char .<br><br> h ed in a variable e to this variable only once, and alue cannot be changed afterwards. In some languages the n l variables are called constants . In Java we usually name final ariables using capital letters: ng totalCars =4637283648392l; In the If you don 9t initialize the variables, Java will do it for you by ning zero to each numeric variable, false to a sig b v ria ere is also a special keyword fin ration, you can assign a value al , and if it 9s us T d cla v this fi a v final String STATE_CAPITAL= "Washington" ; In addition to primitive data types, you can also use Java classes to declare variables.<br><br> Each primitive data type has a corresponding wrapper class, for example Integer , Double , Boolean , etc. These classes have useful methods to convert data from one type to another. While a char data type is used to store only one character, Java also has a class String for working with a longer text, for example: String lastName= "Smith" ; Java, variable names can not start with a digit and can not ontain spaces.<br><br> In c Creation of a Pet et 9s design and create a class Pet . First we need to decide what ld look similar to this one: L actions our pet will be able to do. How about eat, sleep, and say?<br><br> We 9ll program these actions in the methods of the class Pet . We 9ll also give our pet the following attributes: age, height, weight, and color. Start with creating a new Java class called Pet in My First Project as described in Chapter 2, but do not mark the box for creation of the method main() .<br><br> our screen shou Y A bit is the smallest piece of data that can be stored in o bytes in memory. ory. ypes use eight bytes 1 kilobyte (KB) has 1024 bytes 1 megabyte (MB) has 1024 kilobytes 1 gigabyte (GB) has 1024 megabytes memory.<br><br> It can hold either 1 or 0. A byte consists or eight bits. A char in Java occupies tw An int and a float in Java take four bytes of mem Variables of long and double t each.<br><br> Numeric data types that use more bytes can store larger numbers. Java Programming for Kids, Parents and Grandparents 29 ow we are ready to declare attributes and methods in the N class ir bodies in curly class attributes we should pick data types yo should decide if it should take any The method sleep() will just print a message Good night, Pet . Java classes and methods enclose the brace must have a matching closing braces.<br><br> Every open curly brace: To declare variables for for them. I suggest an int type for the age, float for weight and height, and String for a pet 9s color. The next step is to add some methods to this class.<br><br> Before eclaring a method u d arguments and return a value: see you tomorrow 3 it does not need any arguments and will not return any value. class Pet{ int age; float weight; float height; String color; } class Pet{ } method eat(). It will print the message I 9m so hungry&let me have a snack like nachos!<br><br> . The method say() will also print a message, but the pet will csay d (print) the word or a phrase that we give to it. We 9ll pass this word to the method say() as a method argument .<br><br> The method will build a phrase using this argument and will return it back to the calling program. The new version of the class Pet will look like this: The same is true for the This class represents a friendly creature from the real world: Let 9s talk now about the signature of the method sleep() : public class Pet { int age; float weight; float height; String color; ublic void sleep(){ System.out.println( "Good night, see you tomorrow" ); } "I 9m so hungry&let me have a snack like nachos!" ); } } p public void eat(){ System.out.println( public String say(String aWord){ String petResponse = "OK!! OK!!<br><br> " +aWord; return petResponse; } Java Programming for Kids, Parents and Grandparents 31 y other Java prints the same text. looks like this: me text, and this is the meaning of the keyword public void sleep() tells us that this method can be called from an It class ( public ), it does not return any data ( void ). The empty parentheses mean that this method does not have any arguments, because it does not need any data from the outside world 3 it lways a ethod say() The signature of the m public String say(String aWord) This method can also be called from any other Java class, but has to return so String in front of the method name.<br><br> Besides, it expects some text data from outside, hence the argument String aWord . How do you decide if a method should or should not return a value? If a method performs some data manipulations and has to give the result of these manipulations back to a calling class, it has to return a value.<br><br> You may say, that the class Pet does not have any calling class! That 9s correct, so let 9s create one called PetMaster . This class will have a method main() containing the code to communicate with the class Pet .<br><br> Just create another class PetMaster , and this time select the option in Eclipse that creates the method main() . Remember, without this method you can not run this class as a program. Modify the code generated by Eclipse to look like this: o not forget to press Ctrl-S to save and compile this class!<br><br> o k on the Eclipse menus Run , e of the main class: PetMaster . Push rogram will print the following text: 9 K o h Pet reating an eclares a variable myPet and uses operator new : et myPet = new Pet(); a method returns a value, you should call this method in a i iable that has the same type as the e rn v o t e et!!" ); e is stored in the variable e eaction and if you want to see what 9s in there, be my guest: D T run the class PetMaster clic Run& , New and type the nam button Run and the p the I m so hungry&let me have a snack like nachos! !<br><br> OK! O ! !<br><br> Tweet!! Tweet!! od night, see you tomorrow G T e is the calling class , and it starts with c Master of the object Pet .<br><br> It d instance ava the J P This line declares a variable of the type Pet (that 9s right, you can treat any classes created by you as new Java data types). Now the variable myPet knows where the Pet instance was created in the computer 9s memory, and you can use this variable to call any methods from the class Pet , for example: myPet.eat(); If d fferent way. Declare a var r tu alue of the method, and assign it to this variable.<br><br> Now hod: y u can call this met S ring petReaction; p tReaction = myPet.say( "Tweet!! Twe At this point the returned valu p public class PetMaster { public static void main(String[] args) { String petReaction; m.out.println(petReaction); myPet.sleep(); } Pet myPet = new Pet(); myPet.eat(); petReaction = myPet.say( "Tweet!! Tweet!!" ); Syste } tR Java Programming for Kids, Parents and Grandparents 33 ystem.out.println(petReaction); S Inheritance 3 a Fish is Also a Pet Our class Pet will help us learn yet another important feature of Java called inheritance .<br><br> In the real life, every person inherits some features from his or her parents. Similarly, in the Java world you can also create a new class, based on the existing one. The class Pet has behavior and attributes that are shared by many pets 3 they eat, sleep, some of them make sounds, their skins have different colors, and so on.<br><br> On the other hand, pets are different - dogs bark, fish swim and do not make sounds, parakeets talk better than dogs. But all of them eat, sleep, have weight and height. That 9s why it 9s easier to create a class Fish that will inherit some common behaviors and attributes from the lass Pet , rather than creating Dog , Parrot or Fish from scratch very time.<br><br> ou can say that our Fish is a subclass of the class Pet , and the class Pet is a superclass of the class Fish . In other words, you use the class Pet as a template for creating a class Fish . c e A special keyword extends that will do the trick: Y class Fish extends Pet{ } ss Fish as it is now, you can still use ven if you will leave the cla E every method and attribute inherited from the class Pet .<br><br> Take a look: Fish myLittleFish = new Fish(); m yLittleFish.sleep(); e have not declared any methods in the class Fish Pe Even though w yet, we are allowed to call the method sleep() from its superclass! Creation of subclasses in Eclipse is a piece of cake! Select the menus File , New , Class , and type Fish as the name of the class.<br><br> Replace the java.lang.Object in the field superclass with the ord t . w Let 9s not forget, however, that we 9re creating a subclass of a Pet to add some new features that only fish have, and reuse some of the code that we wrote for a general pet. Java Programming for Kids, Parents and Grandparents 35 n dive, but fish certainly can.<br><br> Let 9s add a new ethod dive() to The method dive( fish how deep it should go. We 9ve also declared a class variable currentDepth tha e current depth every dive() . This method returns the current alue of the variable currenDepth to the calling class.<br><br> lease create another class FishMaster that will look like this: ot all pets ca N m the class Fish now. ) has an argument howDeep that tells the t will store and update th time you call the method v P It 9s time to reveal a secret 3 inherited from the super-du all classes in Java are per class Object, regardless if you do use the word or not. But Java classes If this would happen with people, kids would not be subclasses of their parents, but all the boys would descendents of A Eve : .<br><br> extends can not have two separate parents. dam, and all the girls descendents of public class FishMaster { public static void main(String[] args) { Fish myFish = new Fish(); myFish.dive(2); myFish.dive(3); myFish.sleep(); } } public class Fis int currentDe public int d currentDep System.out System.out ntDepth + " feet below sea level" ); return cur } } h extends Pet { pth=0; ive( int howDeep){ th=currentDepth + howDeep; .println( "Diving for " + howDeep + " feet" ); .println( "I'm at " + curre rentDepth; e object Fish and calls its dive() e method sleep it will print the follow Diving for 2 feet I'm at 2 feet belo Diving for 3 feet I'm at 5 feet be o Good night, see you tomorrow Have you noticed that beside methods defined in the class Fish, e FishMaster also calls methods from its superclass Pet ? whole point of inheritance 3 you do not have to copy and paste code from the class Pet 3 just use the word extends , and the class Fish can use Pet 9s methods!<br><br> The method main() instantiates th ethod twice with different arguments. After that, it calls m th () . When you run the program FishMaster , ing messages: sea level w l w sea level th That 9s the One more thing, even though the method dive() returns the value of currentDepth , our FishMaster does not use it.<br><br> That 9s fine, our FishMaster does not need this value, but there may be some other classes that will also use Fish, and they may find it useful. For example, think of a class FishTrafficDispatcher that has to know positions of other fish under the sea before allowing diving to avoid traffic accidents : . Java Programming for Kids, Parents and Grandparents 37 ethod Overriding you kn it aloud).<br><br> But our cl that has a method writing something like this: Fish.say(); r fish started to talk& If you do not want this to happen, Fish has to override the Pet 9s method say() . This is how : if you declare in a subclass a method with exactly the nature as in its superclass, the method of the subclass call to the method main() of the lass FishMaster : M As ow, fish do not speak (at least they do not do ass Fish has been inherited from the class Pet say() . This means tha nothing stops you from t my Well, ou the class it works same sig will be used instead of the method of the superclass.<br><br> Let 9s add the method say() to the class Fish . Now add the following method c myFish.say( "Hello" ); Run the program and it 9ll print on't you know that fish do not talk? Th s been overridden , or in ther words s press Wo D is proves that Pet 9s method say() ha up ed.<br><br> o w! We 9ve learned a lot in this chapter 3 let 9s just take a break. public String say(String something){ return "Don't you know that fish do not talk?" ; } If a method signature includes the keyword final , such m f ethod can not be overridden, for example: inal public void sleep(){&} Additional Reading 1.Java Data Types: http://java.sun.com/docs/books/tutorial/j ava/nutsandbolts/datatypes.html 2.About inheritance: va/co http://java.sun.com/docs/books/tutorial/ja ncepts/inheritance.html Practice 1.<br><br> Create a n following method ew class Car with the s: public void start() public void stop() public int drive( int howlong) rite another class and that r and call its methods. The result of each hod call has to be printed using The method drive() has to return the total distance driven by the car for the specified time. Use the following formula to calculate the distance: distance = howlong*60; 2.<br><br> W CarOwner creates an instance of the object Ca met System.out.println() . Java Programming for Kids, Parents and Grandparents 39 ractice for Smarty Pants P Create a subclass of Car named JamesBondCar and o

less

Copyright © 2010 beepdf.com. All rights reserved.