Introduction to Object-Oriented Programming Lesso n 1: Int ro duct io n: Le arn Obje ct -Orie nt e d Pro gram m ing Using J ava Let's Get Go ing What is Java? What is a Java Applet? Yo ur Very First Applet What Do es It Mean To Co mpile? Brackets and Blo cks o f Co de Lesso n 2: J ava Obje ct s Objects: The So urce o f Java's Po wer Let's Break It Do wn Java Classes and Objects The Structure o f Applets Our Original Example Experiment and Learn! Lesso n 3: Go ing Furt he r wit h J ava Obje ct s Mo re o n Objects Extending a Class Instantiatio n - Creating an o bject to use Instantiating Multiple Objects fro m a Single Class Using Multiple Co nstructo rs Lesso n 4: Variable s Variables: Co ntainers fo r Values Variable Sco pe Accessing Variables fro m Ano ther Class Lesso n 5: Mo re o n Variable s Setting Access Levels and Static Metho ds Setting Access Levels o n Member Variables private pro tected package public Static Variables (also called Class Variables) Final Variables Lesso n 6 : Me t ho ds Metho ds Metho ds Make Things Happen Returning Values Passing Values as Parameters Setting Access Levels o n Metho ds Static Metho ds (Class Metho ds) Lesso n 7: T he J ava API Packages and APIs

Organizing Functio nality Packages: Pre-Made To o ls Using the Java API Where do es it all co me fro m? Where in o ur filesystem are these Java API directo ries? What classes are available in the Java API? Lesso n 8 : Co nt ro l St ruct ure s: Lo o ps Lo o ps Yo ur First Lo o p Fo r Lo o ps Lesso n 9 : Co nt ro l St ruct ure s: If and Swit ch Co ndit io nals Using Co nditio nal Statements fo r Decisio n Making The If Statement If/Else Statements Co mplex Test Clauses Lesso n 10 : Ope rat o rs Operato rs Binary Operato rs Assignment (equals) Additio n Subtractio n Multiplicatio n Divisio n Mo dulus Sho rt-hand Additio n Sho rt-hand Subtractio n Sho rt-hand Multiplicatio n Sho rt-hand Divisio n Sho rt-hand Mo dulus Binary Co nditio nal Operato rs Equality Less Than Greater Than Less Than o r Equal To Greater Than o r Equal To Unary Operato rs Negatio n Increment Decrement Lesso n 11: Dat a-T yping and Co nve rsio n Co nverting Data Types Co nverting Integers to Strings Using Data Types Mo re Static Metho ds--'Sticky Co de'

So , when to co nvert a static reference to a metho d? Lesso n 12: Obje ct Arrays Co nverting Between Data Types The Array Creating Arrays in Java So mething Different Lesso n 13: Advance d Obje ct Orie nt at io n Part I - OO De sign Advanced Object Orientatio n Part I - OO Design Getting 'Object Oriented' What no w? Lesso n 14: Advance d Obje ct Orie nt at io n Part II - Abst ract s Advanced Object Orientatio n - Abstracts Thinking in the Abstract No t Entirely Abstract Variables - Abstract o r No t Lesso n 15: Advance d Obje ct Orie nt at io n - Int e rf ace s Advanced Object Orientatio n - Interfaces Multiple Inheritance Using Interfaces fo r Multiple-Inheritance Style Data-Typing Using Interfaces to Help o ur Waitress Inheritance with Interfaces

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Introduction: Learn Object-Oriented Programming Using Java Welco me to the O'Reilly Scho o l o f Techno lo gy's Object-Oriented Pro gramming using Java co urse.

Course Objectives When yo u co mplete this co urse, yo u will be able to : demo nstrate understanding o f classes, co nstructo rs, o bjects, and instantiatio n. access variables and mo difier keywo rds. develo p metho ds using parameters and return values. build co ntro l structo rs in an o bject-o riented enviro nment. co nvert data types using API metho ds and o bjects. design o bject-o riented pro grams using sco pe, inheritence, and o ther design techniques. create an o bject-o riented applicatio n using Java packages, APIs, and interfaces, in co njunctio n with classes and o bjects. In this co urse, yo u'll be intro duced to the co ncepts, fundamental syntax, and the tho ught pro cesses behind true o bject-o riented pro gramming. Co mpletio n o f this co urse will give yo u the to o ls and basic kno wledge yo u need to learn mo re specific o bjecto riented pro gramming techniques in languages such as Java, C++, C#, and VB.NET. Fro m beginning to end, yo u will learn by do ing yo ur o wn Java applet-based pro jects. These pro jects, as well as the final pro ject, will add to yo ur po rtfo lio and pro vide needed experience. Besides a bro wser and internet co nnectio n, all so ftware is pro vided o nline by the O'Reilly Scho o l o f Techno lo gy.

Learning with O'Reilly School of T echnology Courses As with every O'Reilly Scho o l o f Techno lo gy co urse, we'll take a user-active appro ach to learning. This means that yo u (the user) will be active! Yo u'll learn by do ing, building live pro grams, testing them and experimenting with them— hands-o n! To learn a new skill o r techno lo gy, yo u have to experiment. The mo re yo u experiment, the mo re yo u learn. Our system is designed to maximize experimentatio n and help yo u learn to learn a new skill. We'll pro gram as much as po ssible to be sure that the principles sink in and stay with yo u. Each time we discuss a new co ncept, yo u'll put it into co de and see what YOU can do with it. On o ccasio n we'll even give yo u co de that do esn't wo rk, so yo u can see co mmo n mistakes and ho w to reco ver fro m them. Making mistakes is actually ano ther go o d way to learn. Abo ve all, we want to help yo u to learn to learn. We give yo u the to o ls to take co ntro l o f yo ur o wn learning experience. When yo u co mplete an OST co urse, yo u kno w the subject matter, and yo u kno w ho w to expand yo ur kno wledge, so yo u can handle changes like so ftware and o perating system updates. Here are so me tips fo r using O'Reilly Scho o l o f Techno lo gy co urses effectively: T ype t he co de . Resist the temptatio n to cut and paste the example co de we give yo u. Typing the co de actually gives yo u a feel fo r the pro gramming task. Then play aro und with the examples to find o ut what else yo u can make them do , and to check yo ur understanding. It's highly unlikely yo u'll break anything by experimentatio n. If yo u do break so mething, that's an indicatio n to us that we need to impro ve o ur system! T ake yo ur t im e . Learning takes time. Rushing can have negative effects o n yo ur pro gress. Slo w do wn and let yo ur brain abso rb the new info rmatio n tho ro ughly. Taking yo ur time helps to maintain a relaxed, po sitive appro ach. It also gives yo u the chance to try new things and learn mo re than yo u o therwise wo uld if yo u blew thro ugh all o f the co ursewo rk to o quickly. Expe rim e nt . Wander fro m the path o ften and explo re the po ssibilities. We can't anticipate all o f yo ur questio ns and ideas, so it's up to yo u to experiment and create o n yo ur o wn. Yo ur instructo r will help if yo u go co mpletely o ff the rails. Acce pt guidance , but do n't de pe nd o n it . Try to so lve pro blems o n yo ur o wn. Go ing fro m misunderstanding to understanding is the best way to acquire a new skill. Part o f what yo u're learning is pro blem so lving. Of co urse, yo u can always co ntact yo ur instructo r fo r hints when yo u need them.

Use all available re so urce s! In real-life pro blem-so lving, yo u aren't bo und by false limitatio ns; in OST co urses, yo u are free to use any reso urces at yo ur dispo sal to so lve pro blems yo u enco unter: the Internet, reference bo o ks, and o nline help are all fair game. Have f un! Relax, keep practicing, and do n't be afraid to make mistakes! Yo ur instructo r will keep yo u at it until yo u've mastered the skill. We want yo u to get that satisfied, "I'm so co o l! I did it!" feeling. And yo u'll have so me pro jects to sho w o ff when yo u're do ne.

Lesson Format We'll try o ut lo ts o f examples in each lesso n. We'll have yo u write co de, lo o k at co de, and edit existing co de. The co de will be presented in bo xes that will indicate what needs to be do ne to the co de inside. Whenever yo u see white bo xes like the o ne belo w, yo u'll type the co ntents into the edito r windo w to try the example yo urself. The CODE TO TYPE bar o n to p o f the white bo x co ntains directio ns fo r yo u to fo llo w: CODE TO TYPE: White boxes like this contain code for you to try out (type into a file to run). If you have already written some of the code, new code for you to add looks like this. If we want you to remove existing code, the code to remove will look like this. We may also include instructive comments that you don't need to type. We may run pro grams and do so me o ther activities in a terminal sessio n in the o perating system o r o ther co mmandline enviro nment. These will be sho wn like this: INTERACTIVE SESSION: The plain black text that we present in these INTERACTIVE boxes is provided by the system (not for you to type). The commands we want you to type look lik e this.

Co de and info rmatio n presented in a gray OBSERVE bo x is fo r yo u to inspect and absorb. This info rmatio n is o ften co lo r-co ded, and fo llo wed by text explaining the co de in detail: OBSERVE: Gray "Observe" boxes like this contain information (usually code specifics) for you to observe. The paragraph(s) that fo llo w may pro vide additio n details o n inf o rm at io n that was highlighted in the Observe bo x. We'll also set especially pertinent info rmatio n apart in "No te" bo xes:

Note T ip

No tes pro vide info rmatio n that is useful, but no t abso lutely necessary fo r perfo rming the tasks at hand.

Tips pro vide info rmatio n that might help make the to o ls easier fo r yo u to use, such as sho rtcut keys.

WARNING

Warnings pro vide info rmatio n that can help prevent pro gram crashes and data lo ss.

Altho ugh this is yo ur first Java co urse, yo u'll learn Java using J ava Apple t s (we'll explain what Java Applets are in a minute). Using applets fro m the start is a unique feature o f the OST Java co urse. Mo st o ther co urses begin using text-based pro grams which generally return so me pretty bo ring o utput. We use Java Applets right away because this allo ws yo u to create visually rewarding pro grams early o n. Also , since Java Applets run in a web bro wser, we'll be able to use the web to co mmunicate ideas o n Java pro gramming. In later co urses yo u'll learn ho w to make servlets, do Java pro gramming fo r Windo ws, and o ther co o l stuff.

Let's Get Going What is Java? Java is a pro gramming language o riginally develo ped by Sun Micro systems as an alternative to o ther languages like C++. Befo re Java was created, it was likely that a piece o f so ftware written fo r o ne type o f co mputer wo uld require many changes in o rder to run o n ano ther type o f co mputer. The intentio n with Java was to create a language that wo uld allo w a piece o f so ftware to be written o nce and then be able to run o n many different types o f machines (like tho se running Micro so ft Windo ws, Mac OS, o r UNIX to name a few).

What is a Java Applet? An applet is a Java pro gram that can be sent alo ng with a web page when a user requests the page. A Java Applet runs within a web bro wser. The wo rd "applet" was co ined to mean "small applicatio n." To create an applet, yo u must create so urce files that extend the java.applet.Applet class. If yo u do n't kno w what this means, do n't wo rry, we're just getting started. Fo r no w, just be aware that applets are written in a special way and that yo u need a web bro wser in o rder to run them.

Your Very First Applet At OST we believe in learning by do ing, so let's do so mething! Let's create o ur first Java Applet! Yo u will use Co deRunner to experiment with the lesso n examples. The large white textarea yo u see belo w is the Edito r. This is where yo u'll type yo ur co de. Make sure that yo u are using the pro per synt ax. Lo cate the Synt ax: select bo x o n the Co deRunner to o lbar. Then click o n the select bo x to see a list o f the different mo des that can be used:

In this co urse we will be using o nly the HT ML and J ava syntax mo des o f Co deRunner. Go ahead and select the Java syntax mo de so we can wo rk o n o ur first example. In Java mo de, type the co de belo w as sho wn:

CODE TO TYPE: // These are Java comments. This syntax works for single lines. /* These are also Java comments. Notice the syntax used to implement them. They work over multiple lines. */ import java.applet.*; import java.awt.*; public class CakeApplet extends Applet { public void paint(Graphics g) { g.drawString("I am a Cake.",25, 25); } } Save this file as Cake Apple t .java by clicking the butto n; this is the Actio n Butto n. The Actio n Butto n can do different things depending o n what syntax Co deRunner is set to . In Java syntax mo de, this butto n will save and co mpile yo ur Java file. Yo u must save this file as CakeApplet.java with all capitalizatio n and punctuatio n exactly as yo u see here. Later, yo u'll see why we're so strict abo ut the names yo u give yo ur files. Yo u may no t realize it, but yo u've just created yo ur first Java source file. A so urce file is a set o f programming statements that defines the behavio r o f yo ur pro gram. Just as a recipe is a set o f instructio ns fo r baking a blueberry pie, the statements in yo ur so urce file are instructio ns (in a human-readable fo rmat) given to the co mputer to execute yo ur pro gram. As yo u'll see, this particular pro gram do esn't do anything.

To run the applet that we've just created, and so we can see it o n the web, the applet needs to be embedded within an HTML do cument. We embed applets in much the same way as we embed images in an HTML file. Let's make the HTML file! Click the New File butto n and type the fo llo wing co de into the Edito r belo w:

, be sure to change the syntax mode of CodeRunner to HTML,

CODE TO TYPE:

Go ahead and save this file as Cake Apple t .ht m l, by clicking

and typing "CakeApplet.html" in the Save As field.

No w, let's see what this applet can do . Since yo u've already saved and co mpiled CakeApplet.java, yo u sho uld be able to run it by Previewing the html file. Yo u can do this by clicking the Actio n Butto n while Co deRunner is in HTML syntax mo de. A new windo w o pens that says I am a Cake . Seems like a lo t o f wo rk just to get a message that says "I am a Cake," huh? Thankfully, Java can do much mo re than

just display sho rt messages like this o n a web page.

Note

Yo u can also view yo ur applet in a regular bro wser windo w by go ing to the URL: ht t p://yourlogin.o re illyst ude nt .co m /Cake Apple t .ht m l Be sure to replace yourlogin with the name yo u use to lo g in to these co urses.

Let's take a clo ser lo o k at the HTML file yo u just created. OBSERVE: The height and width o f the applet is co ntro lled by the HEIGHT and WIDT H attributes o f the APPLET tag. In this case, the applet will be 20 0 pixels wide and 20 0 pixels high. Yo u may have no ticed that yo u referenced a file named "CakeApplet.class" using the CODE attribute o f the APPLET tag. Wait a seco nd—didn't we name o ur Java file "CakeApplet.java"? Well, we did. But remember that CakeApplet.java is a so urce file which defines o ur pro gram in human-readable format. We need to co nvert o ur so urce file into a machinereadable format in o rder fo r the co mputer to make sense o f this co de. To acco mplish this, we compile o ur so urce file. It just so happens that co mpiled Java files are given the .class file extensio n. This file is auto matically saved to yo ur acco unt. In the list o f files in yo ur acco unt, yo u see two files: the source file named Cake Apple t .java and the class file named Cake Apple t .class. The class file is the co mpiled versio n o f the so urce file.

What Does It Mean T o Compile?

Yo u're pro bably wo ndering what it means to co mpile a so urce file. Let me give yo u an analo gy that might help yo u understand. Remember the blueberry pie that we were go ing to bake earlier? We co mpared the recipe fo r the pie to the source file used to create o ur pro gram. In the same way that we wo uld then use an oven to transfo rm the raw ingredients into a delicio us blueberry pie, the Java co mpiler tranfo rms o ur so urce file into "bytecode" (machinereadable co de.) The byteco de is then interpreted by the Java Virtual Machine (JVM fo r sho rt). The Java Virtual Machine is either so ftware o r hardware that allo ws yo ur co mputer to run Java pro grams. Once the JVM has interpreted the byteco de, the pro gram is sent to the co mputer in a fo rm that can then be executed. Java so ftware can run o n many different types o f co mputers because the JVM will interpret the pro gram into a fo rm that a particular co mputer can understand. Yo ur Java so urce files will always be co mpiled into files with a .class extensio n. These .class files co ntain the byteco de to be interpreted by a Java Virtual Machine. Since we are using applets to learn Java, the JVM resides in yo ur web bro wser.

Brackets and Blocks of Code Let's take a clo ser lo o k at the Java file we created.

OBSERVE: co de fro m the abo ve example // These are Java comments. This syntax works for single lines. /* These are also Java comments. Notice the syntax used to implement them. They work over multiple lines. */ import java.applet.*; import java.awt.*; public class CakeApplet extends Applet { public void paint(Graphics g) { g.drawString("I am a Cake.",25, 25); } } In o ur example, the blue and re d co de make up o ur co m m e nt s. Co mments do n't really do anything— they're simply no tes to anyo ne who happens to lo o k at the so urce co de. As o ur sample co mments explain, co mments are lines that the Java co mpiler igno res. The lines preceded by pairs o f // (fo rward slashes) and co ntained within /* and */ (fo rward slash and an asterisk) are igno red by the co mpiler. Usually yo u'll see co mments used at the beginning o f pro grams to give info rmatio n abo ut the autho r, co pyright info rmatio n, and so me no tes abo ut what the pro gram do es. Next, we see package s that need to be impo rted into o ur pro gram. Packages are impo rted so that we can include co de in o ur pro gram. Altho ugh we canno t see the packages within the co de in the bo x abo ve, they are being used. This co ncept may be a bit co nfusing right no w, but do n't wo rry if yo u do n't quite understand it yet. We will discuss it in depth later.

Note

There is a semico lo n (;) at the end o f each o f these lines. Semico lo ns are used to indicate the end o f a co mmand. Yo u must use a semico lo n at the end o f each co mmand.

Blo cks o f co de are defined using curly brackets, o r braces ({ and } ). The o ut side blo ck o f co de is a Class. Again, do n't panic if this isn't perfectly clear to yo u just yet. We'll learn a lo t mo re abo ut this later. No tice that the inside blo ck o f co de is indented. We purpo sely indent this co de (including the clo sing brace) so that we can tell where the blo cks o f co de begin and end. Thro ugho ut the co urse, practice using the same indentatio ns yo u see in o ur examples so that yo ur co de will be mo re readable. After yo u write a few pro grams it will co me to yo u naturally! Co ngratulatio ns o n co mpleting the first steps to ward learning Java! We've go t a lo ng way to go , but yo u've already learned the building blo cks yo u'll need to beco me a skilled Java Applet pro grammer. See yo u at the next lesso n. Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Java Objects Objects: T he Source of Java's Power In the last lesso n, we co mpiled o ur first Java Applet. We also learned what it means to co mpile a Java so urce file. But we still do n't kno w what the co de in the so urce file is actually do ing. Over the next few lesso ns, we'll break do wn o ur applet so urce file to get a better understanding o f that. We'll lo o k at the big picture first, then examine big chunks o f co de to understand what each o ne do es, and eventually go o ver each individual line o f co de. By appro aching o ur task this way, we'll understand Java's structure first, and then have a fo undatio n fro m which to explo re the details.

Let's Break It Down Yo u created two files in the previo us lesso n—an applet named CakeApplet.java and an HTML page named CakeApplet.html. We used the HTML page to call the applet. Open these files in the Co deRunner Edito r by finding them in the File Bro wser, to the left o f this frame:

Do uble-click each file to lo ad it into the Co deRunner Edito r. Co deRunner auto matically o pens the files in the co rrect Syntax Mo de. OBSERVE: yo ur HTML file We called the applet using CakeApplet.class, even tho ugh we named the file CakeApplet.java.

OBSERVE: Yo ur Java Applet // These are Java comments. This syntax works for single lines. /* These are also Java comments. Notice the syntax used to implement them. They work over multiple lines. */ import java.applet.*; import java.awt.*; public class CakeApplet extends Applet { public void paint(Graphics g) { g.drawString("I am a Cake.",25, 25); } } This applet printed the wo rds "I am a Cake" to the screen. We'll discuss the details later, but befo re we do , let's talk a little abo ut classe s and o bje ct s—we'll enco unter these wo rds o ften thro ugho ut the co urse.

Java Classes and Objects Yo u may no t have realized it, but creating that applet was yo ur first expo sure to a J ava class de f init io n. The wo rd "class" has a unique definitio n in Java. In Java, class is defined as the blueprint that describes the pro perties and metho ds o f a specific o bject. So what are o bjects in Java? Fo r that matter, what are pro perties and metho ds in Java? We used a cake in o ur latest example, so let's use a cake to understand these co ncepts to o . Think o f a Java o bject as a cake (we co uld use any real-wo rld o bject, but I happen to like cake). A cake has vario us pro perties, such as flavo r and co lo r. Pro perties o f Java o bjects are similar. Think o f Java pro perties as adjectives that describe Java o bjects. Staying with o ur analo gy, a metho d in Java wo rks like a verb. Metho ds describe actio ns that can typically be applied to the o bject. A metho d o f a cake o bject might be to eat, deco rate, o r taste it. In Java, we use parentheses to indicate a metho d, so yo u wo uld use e at (), de co rat e (), o r t ast e (). So far then, we kno w that: A pro perty is an attribute that describes an o bject. It is like an adjective. A metho d is so mething we do to o r o n an o bject. It is like a verb. In o ur example, the class de f init io n creates a Cake Apple t class. Think o f the class definitio n as a cake pan that helps create cakes. Different cake pans can make different shapes o r types o f cakes. A specific cake pan is a template fo r each cake that will be made using that particular pan. That is, every cake made with that pan will have the same shape and will be deco rated the same way. In this case, Cake Apple t creates an applet that can be run in a web bro wser.

The Cake Apple t class is like a mo ld fo r making cake o bjects.

Creating a cake o bje ct called m yCake ...

A cake o bje ct called m yCake .

We still haven't created any o bjects using the co de in the example in the bo x abo ve. But so o n eno ugh, we'll learn ho w to use o ur class to make o bjects that we can use and reuse. In the same way that we can make as many cakes as we want to using the same pan, we can make as many o bjects as we want to using the same class.

A Cake o bje ct called m yCake

One Cake class can be used to create many Cake o bjects.

A Cake o bje ct called hisCake

A Cake o bje ct called he rCake A class is a template o r blueprint fo r an o bject, just like a cake pan is a template o r blueprint to make cakes. OBSERVE: Yo ur Java Applet public class CakeApplet extends Applet { We wo n't wo rry abo ut the wo rd public right no w, but yo u can pro bably guess that it has so mething to do with classes being made available fo r everyo ne to use. We have to declare classes as o ne o f three types —public, privat e , o r pro t e ct e d. Private and pro tected class declaratio ns are used to guard against the co nfusio n that co uld o ccur if two different pro grammers use the same class name. Mo stly, the classes we create will be declared as public, altho ugh we will discuss private and pro tected classes in mo re detail later. In this line o f co de, we declare a new class named Cake Apple t . The CakeApplet class definitio n lays o ut the vario us pro perties and metho ds that each CakeApplet o bject will have. The seco nd part o f o ur class definitio n says e xt e nds Apple t . Just as o ur CakeApplet is a Java class, so is Apple t . But we didn't create the Applet class—Oracle did it fo r us. There are many o ther classes like this that have been created by Oracle and o ther peo ple and made available fo r us to use. One o f the great advantages o f o bject-o riented pro gramming languages is that we can use and reuse o ur classes, as well as classes o ther pro grammers have already created. Pro grammers make classes and o bjects available to each o ther all o ver the wo rld. This makes creating new pro grams and o bjects much easier. To beco me a Java pro grammer, yo u need to be able to create yo ur o wn Java classes, and also kno w ho w to use classes that o ther peo ple have already written. The Apple t class was designed to give new pro grams (such as o ur Cake Apple t ) the de f ault info rmatio n required to functio n within a web bro wser enviro nment. The Applet class is a mold for making applets. We can use it witho ut kno wing specifically ho w it was made o r seeing any o f the co de used to create it, just like we can use a cake pan witho ut kno wing ho w it was made o r fro m what material. Also , the Apple t class defines security limitatio ns and o ther features that all Java applets must fo llo w. So , ho w do es o ur CakeApplet access these pro perties and features? Our CakeApplet inherits them by defining the Apple t class as a supe r-class. By e xt e nding the Apple t class, o ur CakeApplet (the sub-class) is given all o f the pro perties o f the super-class. Then o ur CakeApplet has the ability to change tho se pro perties and/o r add new pro perties witho ut requiring us to create them fro m scratch. It's as if we are given a mo ld, and then given the ability to make a mo re co mplicated mo ld by adding pieces to it. In the next part o f the co de, we use two metho ds that are available thro ugh the Applet class. OBSERVE: public void paint(Graphics g) { g.drawString("I am a Cake.",25, 25); }

This is the part o f the co de that do es the wo rk. Fo r this pro gram, it prints the wo rds I am a Cake to the screen. We use the m e t ho d named paint (). Again, we use the wo rd public, a sure sign that we are declaring so mething. Next, we see the wo rd vo id. This indicates the type o f data the metho d will return. Think o f a metho d as a machine that do es so mething. Our paint () metho d do es so mething to o . Ho wever, it do esn't return anything that can be used elsewhere, so we use the wo rd vo id. Next we see paint (Graphics g). This time we do n't have a cho ice abo ut the name. We have to call this metho d paint (). This metho d requires a Graphics o bject as a parameter, so we pass it a Graphics o bject that we name g. That's a lo t to digest all at o nce! Do n't wo rry, we'll discuss parameters in greater detail later. Fo r no w, be aware that we co uld have named the Graphics o bject anything we wanted; we just cho se g fo r Graphics. And, lo gically, the Graphics o bject is used to create graphics. Because we have used the Graphics o bject, we can no w use any o f the metho ds and pro perties asso ciated with it. drawst ring is o ne o f these metho ds. drawst ring allo ws us to write a string o f characters to the screen. drawst ring takes three parameters—the string, the ho rizo ntal po sitio n o f the string, and the vertical po sitio n o f the string. In this case, the wo rds I am a Cake make up the string. It will be lo cated 25 pixels to the right and 25 pixels do wn fro m the upper left co rner o f the applet area.

T he Structure of Applets Applets have a special structure. Because applets live o n a web page displayed by yo ur bro wser, applets must be secure and execute upo n lo ading. To start and execute the applet, the JVM auto matically calls certain metho ds that are present within the applet. One o f the metho ds that the JVM calls auto matically is paint (). Others include init (),st art (), st o p(), and de st ro y(). These metho ds are called regardless o f whether they are listed in o ur pro gram. We put them in o ur applet in o rder to add functio nality to them as they are called. Fo r instance, we added co de to the paint () metho d to print I am a Cake to the screen. When the page is lo aded, the metho ds are called in the fo llo wing o rder: 1. init (): called as the applet gets to the bro wser 2. st art (): called when the HTML page is co mpletely lo aded 3. paint (): called after start(); supplies graphics and text to the applet 4. st o p(): called after paint(); sto ps the applet 5. de st ro y(): called after sto p(); clears memo ry after the applet is finished executing If we want so mething to happen, we have to put the co de that makes it happen within o ne o r mo re o f tho se metho ds, just like we did in the paint () metho d abo ve. Later we'll try using o ther metho ds fro m within the paint metho d. To help illustrate these co ncepts mo re clearly, let's create an applet that sho ws the life cycle o f an applet. Just like befo re, start by clicking the New File co de into the Edito r:

butto n, and set the Syntax Mo de to Java. No w, type the fo llo wing

CODE TO TYPE: import java.applet.*; import java.awt.*; public class AppletLifeCycle extends Applet { StringBuffer buffer; public void init() { buffer = new StringBuffer(); addItem("initializing the Applet "); } public void start() { addItem("starting the Applet "); } public void stop() { addItem("stopping the Applet "); } public void destroy() { addItem("preparing for unloading"); } void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); } public void paint(Graphics g) { //Draw a Rectangle around the applet's display area. g.drawRect(0, 0, getSize().width - 1, getSize().height - 1); //Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15); } }

Save the file as Apple t Lif e Cycle .java and click the Co mpile butto n appears saying "No Syntax Erro rs." Remember, we'll need an HTML file to run the Applet. Click the New File Syntax Mo de, and enter the fo llo wing HTML file:

. A dialo gue bo x

butto n again, switch to HTML

CODE TO TYPE: HTML file fo r Previewing the abo ve Applet

Save the HTML co de as Apple t Lif e Cycle .ht m l and click .

Note

The Actio n Butto n behaves differently depending o n what Syntax Mo de Co deRunner is currently set to . In HTML Syntax Mo de, the Actio n Butto n previews the current do cument. In Java Syntax Mo de, the Actio n Butto n saves and co mpiles o ur Java files. The Save Butto n merely saves a Java file, but do es no t co mpile it.

The wo rds "Initializing the Applet" and "Starting the Applet" are printed by the init () and st art () metho ds. But why didn't o ur st o p() and de st ro y() metho ds display their messages? Our st o p() and de st ro y() metho ds were indeed called, but by the time they were called, the bro wser no lo nger allo wed o ur Applet to mo dify the screen. So , the wo rds "sto pping the Applet" and "preparing fo r unlo ading" were never displayed.

Our Original Example Let's go back to o ur CakeApplet example. Open bo th CakeApplet.java and CakeApplet.html in the Co deRunner edito r. We'll create a metho d to be used with o ur CakeApplet class. Because we are creating the metho d o urselves, we can name it whatever we want. Let's call it f ro st Cake (). f ro st Cake () will accept two parameters: the co lo r o f the fro sting and a graphics o bje ct . We must pass a graphics o bject in o rder to actually display the co lo r. Edit yo ur Cake Apple t .java co de to lo o k like the fo llo wing: CODE TO TYPE: import java.applet.*; import java.awt.*; public class CakeApplet extends Applet { public void paint(Graphics g) { frostCake(Color.blue,g); g.setColor(Color.black); g.drawString("I am a BLUE cake.",25, 25); } public void frostCake(Color myColor, Graphics myGraphics) { myGraphics.setColor(myColor); myGraphics.fillRect(0, 0, 50, 50); } } Save and co mpile this file and preview it when pro mpted. It sho uld be a little mo re interesting no w. The bro wser executes the paint () metho d auto matically, but it wo n't execute f ro st Cake () unless we specifically tell it to do so . Therefo re, we call f ro st Cake () fro m inside the paint () metho d. This is the reaso n we added the first line to the paint () metho d. OBSERVE: frostCake(Color.blue,g); When calling f ro st Cake (), we send it two parameters. The first parameter is Co lo r.blue , which indicates that we want to pass the blue pro perty o f the Co lo r o bject to the metho d. The seco nd parameter is g. Recall that we have already defined g as a graphics o bject in the paint ()metho d. Let's take a clo ser lo o k at the f ro st Cake () metho d:

OBSERVE: public void frostCake(Color myColor, Graphics myGraphics) { myGraphics.setColor(myColor); myGraphics.fillRect(0, 0, 50, 50); } Again, we use public vo id to indicate that we are declaring a new metho d. Inside the parentheses are Co lo r m yCo lo r and Graphics m yGraphics. These define the types o f data that the metho d expects. In o ther wo rds, the f ro st Cake () metho d expects to be passed a co lo r and a graphics o bject each time it is called. The values o f these parameters can change each time the metho d is called, but it will no t execute unless it is passed the same types o f values as tho se given in the definitio n. Fo r the first parameter we use a variable we named m yCo lo r. m yCo lo r is a variable o f type Co lo r. We will discuss variables mo re in the next lesso n. Fo r no w, think o f variables as co ntainers to ho ld values. This value can change (which is why it is called a variable), but it is always held in the same lo catio n. In Java, we must describe the kind o f co ntainer it will be o nce the variable is defined. There are many pre-existing types o f co ntainers in Java, and Co lo r is o ne o f them. Fo r the seco nd parameter we use a Graphics o bject named m yGraphics. This is the same type o f o bject as the graphics o bject g we used earlier. Next, we see m yGraphics.se t Co lo r(m yCo lo r). se t Co lo r() is a pre-existing metho d that is accessible thro ugh the Graphics o bject m yGraphics. se t Co lo r() requires a parameter—the co lo r we want m yGraphics to be. We use se t Co lo r() in the paint () metho d as well. In the paint () metho d, we use g.se t Co lo r(Co lo r.black). This means that when the next statement g.drawSt ring(" I am a blue cake ." ,25 , 25 ) is executed, a black co lo r will be used. That's why the wo rds I am a blue cake . are written in black when yo u preview the applet. When we use the se t Co lo r() metho d within the f ro st Cake () metho d, we use m yGraphics.se t Co lo r(m yCo lo r). Because we have passed Co lo r.blue to the f ro st Cake () metho d, when we call it, the statement m yGraphics.se t Co lo r(Co lo r.blue ) is actually being executed. So when the next statement, m yGraphics.f illRe ct (0 , 0 , 5 0 , 5 0 ) is executed, a blue co lo r is used, and the rectangle is blue when yo u preview the applet. We've co vered a lo t o f co mplicated ideas here. The mo st impo rtant part to understand is the structure o f applets. As we mo ve thro ugh the co urse, we'll learn mo re abo ut the specifics. By reco gnizing the co rrect structure, yo u're ready to play aro und with co de and see results.

Experiment and Learn! Try changing the co lo r o f the rectangle to green in two different ways. First, change the co lo r within the paint () metho d. Save/Co mpile and preview yo ur co de and see if it wo rks. Then, change the co lo r within the f ro st Cake () metho d. Try to create yo ur o wn applet based o n what we've do ne so far. Yo u can add so me o ther metho ds to o ur CakeApplet.java file. We've o nly used se t Co lo r, drawSt ring, and f illRe ct . Go to Oracle's website to check o ut a list o f the available metho ds alo ng with sho rt descriptio ns o f each o ne. Try to get at least o ne o ther metho d wo rking in yo ur CakeApplet.java pro gram. Go o d luck! Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Going Further with Java Objects More on Objects Welco me back. In this lesso n we'll go o ver o bje ct s in greater detail and lo o k at two co ncepts related to using classes and o bjects. The first co ncept is e xt e nding classes. In the last lesso n, we created the CakeApplet class by extending the applet class. The applet class was created by so meo ne else. Next, we'll create a new class by extending a class that we create o urselves. Finally, we'll co mpare extending classes to inst ant iat ing o bjects.

Extending a Class OBSERVE: co de fro m the last lesso n import java.applet.*; import java.awt.*; public class CakeApplet extends Applet { public void paint(Graphics g) { frostCake(Color.blue,g); g.setColor(Color.black); g.drawString("I am a BLUE cake.",25, 25); } public void frostCake(Color myColor, Graphics myGraphics) { myGraphics.setColor(myColor); myGraphics.fillRect(0, 0, 50, 50); } } No w, let's create an applet that's just like this o ne, but make the cake red. Instead o f rewriting all o f the co de, we can e xt e nd o ur CakeApplet and make ano ther class that uses so me o r all o f the functio nality o f the CakeApplet class. Make a new file, set the Syntax Mo d to Java and type the the co de belo w into the Edito r: CODE TO TYPE: import java.applet.*; import java.awt.*; public class RedCakeApplet extends CakeApplet { public void paint(Graphics g) { frostCake(Color.red, g); g.setColor(Color.black); g.drawString("I am a RED Cake.",25, 25); } } No w make a new file in HTML Syntax Mo de and type the this co de into the Edito r belo w: CODE TO TYPE:

Save the HTML file as RedCakeApplet.html. Switch back to Java and Save/Co mpile the applet as RedCakeApplet.java. When pro mpted, Preview the applet. Yo u get the same result as befo re, except this time the cake is red. In o ur new Java file we e xt e nde d the CakeApplet class that we created earlier. That is, we to o k all o f the abilities and pro perties o f the CakeApplet class and mo dified them slightly. No tice that we are also using the paint () metho d in o ur new class. The new paint () metho d o ve rride s the paint () metho d previo usly defined in Cake Apple t . That is, the new o ne replaces the o ld o ne. But we didn't o ve rride the f ro st Cake () metho d. We used it as it was already written. We were able to do that because the f ro st Cake () metho d was defined in the CakeApplet class we extended. In fact, we were also able to use the paint metho d (which was defined in the Applet class) because CakeApplet extended Applet. When we call the f ro st Cake metho d, we are using a metho d that we inhe rit e d fro m CakeApplet. When we call the paint metho d, we are using a metho d that we inherited fro m CakeApplet, which inherited it fro m Applet. And we are passing a different co lo r (Co lo r.re d) to the fro stCake metho d, which makes the rectangle red. Our RedCakeApplet is, in every way, a CakeApplet. RedCakeApplet is also an Applet, because CakeApplet e xt e nds Apple t . RedCakeApplet has all o f the functio nality o f o ur CakeApplet class and the Applet class. We can make RedCakeApplet mo re co mplex than CakeApplet by adding functio nality to RedCakeApplet. This relatio nship between classes is called inhe rit ance . In Java, a class can o nly have o ne supe r-class (a class fro m which it extends and inherits). But a class can have any number o f sub-classe s. These subclasse s are also kno wn as childre n. Fo r example, if we made a Yello wCakeApplet and GreenCakeApplet to go alo ng with o ur RedCakeApplet, all three classes wo uld be children o f CakeApplet. If we changed the CakeApplet supe r-class, all three sub-classe s wo uld be effected. Ho wever, if we changed o ne o f the subclasse s there wo uld be no effect o n CakeApplet o r the o ther sub-classes. Class inheritance is similar to genetic inheritance in nature. The o nly majo r difference is that classe s can inhe rit f ro m o nly o ne supe r-class. Here's a graphical representatio n o f this co ncenpt:

Classes are like the strange fish abo ve that have o nly o ne parent.

Instantiation - Creating an object to use Okay, no w suppo se we do n't want o ur Java pro gram to inherit all o f the pro perties o f ano ther class, but we still want to use the functio nality available thro ugh that class. Or, maybe we want to extend o ne class and use functio nality fro m ano ther class. In Java we can o nly e xt e nd o ne class when creating a new class. This can be limiting, especially when we want to use the functio nality o f the hundreds o f classes available in Java. Fo rtunately, we can handle such situatio ns by creating a new applet. Create a new Java file and then type the co de belo w into the Edito r:

CODE TO TYPE: import java.awt.*; public class Cake { int topLocation; int leftLocation; public Cake(int top, int left) { topLocation = top; leftLocation = left; } public void frostCake(Color myColor, Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); g.drawString("I am a Cake.", leftLocation + 50, topLocation + 50); } } Save/Co mpile this file using the name Cake .java. We are unable to preview this file because it's no t an applet, it's just a class file called Cake .class. If yo u check the list o f files in yo ur acco unt, yo u'll see this file included no w. No w that yo u've successfully saved and co mpiled this file, let's create a new applet that will use the Cake class we just created. We'll call o ur new applet Ne wCake Apple t .java. In Java Syntax Mo de, create a new file and type the co de belo w into the Edito r: CODE TO TYPE: import java.applet.*; import java.awt.*; public class NewCakeApplet extends Applet { Cake myCake; public void init() { myCake = new Cake(0,0); } public void paint(Graphics g) { myCake.frostCake(Color.red, g); } } Next, we need to call the co nst ruct o r. After all, the cake has to be made, right? The co nstructo r is like the chef who bakes the cake. We call the co nstructo r in the init () metho d because making the cake is an intializatio n. Alternatively, we co uld have put it in the st art () metho d--either way is fine, so lo ng as we call it using o ne o f the metho ds that is auto matically called befo re the paint () metho d. The syntax used to call the co nstructo r lo o ks like this: m yCake = ne w Cake (0 ,0 ); With this co de, yo u create a ne w Cake using the Cake class which was created in Cake.java. This particular class takes (0 ,0 ) as its parameters. (Yo u'll see why when we discuss the Cake class later.) Because myCake is a type o f Cake, we can use all o f the pro perties and metho ds asso ciated with Cake, including the f ro st Cake () metho d. Here's ho w we call the f ro st Cake () metho d:

OBSERVE: public void paint(Graphics g) { myCake.frostCake(Color.red, g); }

We use the paint () metho d to call f ro st Cake (). Because the f ro st Cake () metho d can no w be accessed thro ugh the myCake o bject, we must use do t no t at io n, like this: m yCake .f ro st Cake (Co lo r.re d, g); This pro cess is called inst ant iat io n. We created an instance o f an o bject that was created in o ur o ld class, within o ur new class. Let's take a clo ser lo o k at ho w we created the Cake class: OBSERVE: import java.awt.*; public class Cake { int topLocation; int leftLocation; public Cake(int top, int left) { topLocation = top; leftLocation = left; } public void frostCake(Color myColor, Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); g.drawString("I am a Cake.", leftLocation + 50, topLocation + 50); } } Our Cake class definitio n is different fro m the class definitio ns we've used befo re in that it do esn't extend applet. That's because Cake isn't an applet, it's just a class, so it do esn't have the paint () metho d o r any o f the o ther self-calling metho ds available fo r use. Let's check o ut the first few lines o f o ur Cake class definitio n: OBSERVE: int topLocation; int leftLocation; public Cake(int top, int left) { topLocation = top; leftLocation = left; }

First, we declare two variables. We'll co ver variables in greater detail later in the co urse. Fo r no w, be aware that yo u must always declare a variable befo re yo u use it, by specifying the type o f variable it is. In this case, bo th o f o ur variables are o f type int , which means that the value sto red in these variables will always be an integer. The names o f o ur new variables are t o pLo cat io n and le f t Lo cat io n. Next, we declare a special kind o f metho d called a co nst ruct o r. In o rder to inst ant iat e an o bject, yo u must

Next, we declare a special kind o f metho d called a co nst ruct o r. In o rder to inst ant iat e an o bject, yo u must have a co nst ruct o r. Yo u can always reco gnize co nstructo rs because they always have the sam e nam e as t he class f ro m which yo u are inst ant iat ing t he o bje ct . Because we are instantiating the Cake o bject, the co nstructo r is named Cake . Co nstructo rs are used to initialize the o bject's member variables. This particular co nstructo r takes two parameters: int t o p and int le f t . These will be used to determine where the cake will be co lo red and where the wo rds I am a Cake will be written. A class can have as many co nstructo rs as yo u like, and each co nstructo r can have as many parameters as yo u like. Because an o bject needs a co nstructo r in o rder to be instantiated, a co nstructo r will auto matically be generated if yo u do no t declare o ne. This default co nstructo r will have no parameters. Once the co nstructo r is defined, the f ro st Cake () metho d is declared. The f ro st Cake () metho d we're using here is essentially the same as the f ro st Cake () metho d used in CakeApplet.java. That is, we are using the metho d to co lo r the cake and to write I am a Cake . The main difference between the two metho ds is that we are using the variable's le f t Lo cat io n and t o pLo cat io n in the new f ro st Cake () metho d: OBSERVE: public void frostCake(Color myColor, Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); g.drawString("I am a Cake.", leftLocation + 50, topLocation + 50); } } So where do we get the value o f these variables? Remember, we called the co nstructo r in Ne wCake Apple t : m yCake = ne w Cake (0 ,0 ); This creates a ne w Cake . The value o f the t o p and le f t parameters in the Cake co nstructo r will be set equal to 0 and 0 . In o ther wo rds, t o p=0 and le f t =0 . This also means that the value o f t o pLo cat io n is equal to 0 and the value o f le f t Lo cat io n is equal to 0 .

Instantiating Multiple Objects from a Single Class While yo u're still in Java Syntax Mo de, mo dify NewCakeApplet.java to lo o k like this: CODE TO EDIT: import java.applet.*; import java.awt.*; public class NewCakeApplet extends Applet { Cake myCake,yourCake; public void init() { myCake = new Cake(0,0); yourCake = new Cake(100,0); } public void paint(Graphics g) { myCake.frostCake(Color.red, g); yourCake.frostCake(Color.blue, g); } } Save/Co mpile this file, naming it NewCakeApplet.java, then preview it with HTML. So , what have we do ne? There are two co lo red rectangles and two lines o f text that read I am a Cake . We inst ant iat e d two ne w Cake o bjects. We used m yCake , just like we did the first time. We also declared yo urCake as a ne w Cake .

We passed different values fo r t o p and le f t when we called the co nstructo r. We set the po sitio n pro perties o f yo urCake so that they were a little different fro m myCake. When we called the f ro st Cake () metho d thro ugh yo urCake , we passed a dif f e re nt co lo r than the o ne we used fo r m yCake . That's why yo urCake is blue and m yCake is st ill re d. By inst ant iat ing two Cake o bjects, we have created two o bjects fro m the Cake class, each with different pro perties.

Using Multiple Constructors Each class can have as many co nstructo rs as yo u want them to have. Yo u might need mo re than o ne co nstructo r in o rder to set different pro perties when yo u instantiate an o bject fro m that class. Switch back to the Cake .java file in the Co deRunner Edito r so we can add ano ther co nstructo r to the Cake class. In Java Syntax Mo de, type the co de belo w into the Edito r: CODE TO TYPE: import java.awt.*; public class Cake { int topLocation; int leftLocation; String cakeFlavor; public Cake(int top, int left) { topLocation = top; leftLocation = left; cakeFlavor = ""; } public Cake(int top, int left, String flavor) { topLocation = top; leftLocation = left; cakeFlavor = flavor; } public void frostCake(Color myColor, Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); g.drawString("I am a" + cakeFlavor + "Cake.", leftLocation + 50, topLoca tion + 50); } } Save/Co mpile this file using the name Cake .java. Befo re we test this o ut, let's lo o k at what we did. We created ano ther co nstructo r fo r Cake. It lo o ks almo st exactly like the first co nstructo r, but with o ne impo rtant difference—this co nstructo r is defined using three parameters. OBSERVE: the first co nstructo r public Cake(int top, int left) { topLocation = top; leftLocation = left; cakeFlavor = ""; }

OBSERVE: the seco nd co nstructo r public Cake(int top, int left, String flavor) { topLocation = top; leftLocation = left; cakeFlavor = flavor; }

The seco nd co nstructo r uses t o pLo cat io n and le f t Lo cat io n as parameters, just like the first co nstructo r do es. But it also uses a third parameter called cake Flavo r. We use this variable in the f ro st Cake () metho d to indicate the flavo r o f the Cake when we write text to the screen. No w we have two co nstructo rs—o ne that sets the cakeFlavo r and o ne that do es no t. We declared the cake Flavo r variable just like we declared t o pLo cat io n and le f t Lo cat io n. cake Flavo r is a St ring variable. We've also mo dified o ur o riginal co nstructo r by adding the cake Flavo r. This pro perty is initialized to an empty string, which ensures that the cakeFlavo r pro perty is always defined. In this case, cakeFlavo r is a string variable: OBSERVE: String cakeFlavor;

No w let's use these two different co nstructo rs. In the Co deRunner Edito r, switch back into the Ne wCake Apple t .java file and make the necessary changes. Edit NewCakeApplet so it lo o ks like this: CODE TO TYPE: import java.applet.*; import java.awt.*; public class NewCakeApplet extends Applet { Cake myCake, yourCake, anotherCake; public void init() { myCake = new Cake(0,0); yourCake = new Cake(100,0); anotherCake = new Cake(0,100,"lemon"); } public void paint(Graphics g) { myCake.frostCake(Color.red,g); yourCake.frostCake(Color.blue,g); anotherCake.frostCake(Color.yellow,g); } } Save/Co mpile this file using the name Ne wCake Apple t .java. Make sure yo u have the appro priate HTML file so yo u can preview the applet with HTML. This time, we instantiated t hre e o bje ct s fro m the Cake class. The first two o bjects (m yCake and yo urCake ) use o nly the first co nstructo r, so they lo o k the same as they did befo re. The third o bject (ano t he rCake ) uses the seco nd co nstructo r. The value o f the cake Flavo r variable is set equal to le m o n. Nice wo rk. Yo u're do ing great so far, already instiating three o bjects fro m a class--go o d jo b! We'll create and use lo ts mo re classes and co nstructo rs as we co ntinue thro ugh the co urse. Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Variables Variables: Containers for Values So far, we've lo o ked at several examples o f Java Applets and go tten a better understanding o f the structure o f Java pro grams. We also learned abo ut variable s. A variable is a co nt aine r that allo ws us to sto re info rmatio n temporarily by giving that info rmatio n a unique name. In this lesso n we'll delve deeper still into variable s and ways to use them. Let's get started! Open the latest versio n o f Cake .java into the Co deRunner Edito r: OBSERVE: Cake.java import java.awt.*; public class Cake { int topLocation; int leftLocation; String cakeFlavor; public Cake(int top, int left) { topLocation = top; leftLocation = left; cakeFlavor = ""; } public Cake(int top, int left, String flavor) { topLocation = top; leftLocation = left; cakeFlavor = flavor; } public void frostCake(Color myColor, Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); g.drawString("I am a" + cakeFlavor + "Cake.", leftLocation + 50, topLocation + 50); } } The Cake class we created in the last lesso n made extensive use o f variables. All o f that bo ld co de in the bo x abo ve are variables. Each light blue variable (such as t o p) is a type o f variable called a param e t e r. The value o f each variable is set with the assignment o perato r = (an equals sign). Alternatively, the value can also be set when the metho d is called. The values o f t o p and le f t were set when the co nstucto r Cake (0 ,0 ) was called in Ne wCake Apple t .java: m yCake = ne w Cake (0 ,0 ); This co de set the value o f t o p equal to 0 and the value o f le f t equal to 0 . Variables must be de clare d. That is, the name o f the variable and its dat a t ype must be set befo re the variable can be used. Fo r example, the fo llo wing variables are declared as data types int and St ring in Cake .java: OBSERVE: Declaring variables int topLocation; int leftLocation; String cakeFlavor;

int is an abbreviatio n fo r int e ge r. When we declare a variable o f type int we are specifying that the variable will o nly ho ld values that are integers. int is kno wn as a prim it ive data type, which means that it is built into Java. This table details all o f the primitive data types available in Java: T ype

Size

bo o le an 8 bits

Allo we d Value s true o r false

char

16 bits single lo wer/upper case letter, single digit, special characters ($, *, etc.), and escape sequences

byt e

8 bits

sho rt

16 bits -32,76 8 to 32,76 7

int

32 bits -2,147,48 3,6 48 to 2,147,48 3,6 47

lo ng

6 4 bits -9 ,223,372,0 36 ,8 54,775,8 0 8 to 9 ,223,372,0 36 ,8 54,775,8 0 7

f lo at

32 bits -3.40 29 234E+38 to 3.40 29 234E+38

do uble

6 4 bits -1.79 76 9 31348 6 23157E+30 8 to 1.79 76 9 31348 6 23157E+30 8

-128 to 127

We'll use all o f these data types during this co urse. Here are so me examples o f ho w different values might appear and their co rrespo nding data types: Lit e ral

Dat a T ype

178

int

8864

lo ng

37.26 6

do uble

8 7.36 3

flo at

26 .77e3 do uble 'c'

char

true

bo o lean

false

bo o lean

The o ther data type used in o ur sample co de abo ve is St ring. St ring is no t a primitive data type. It's a data type kno wn in Java as a re f e re nce . A reference is any data type that is no t primitive, usually a class, an array, o r an int e rf ace . We'll discuss arrays and interfaces later. Fo r no w, let's fo cus o n classes. Recall that we can declare a class to be o f the Cake data type, as we did in in Ne wCake Apple t .java: Cake m yCake ; And in the way we created the Cake class, so meo ne else created the St ring class, so we can use St ring as a data type as well. A St ring is a sequence o f characters. The String class uses the primitive data type char to create a string o bject. Every time yo u want to print text to the screen, yo u use a string. In fact, we did that when we used the g.drawSt ring() metho d: g.drawSt ring(" I am a " + cake Flavo r + " Cake ." , le f t Lo cat io n + 5 0 ,t o pLo cat io n + 5 0 ); See the quo tatio n marks aro und I am a and Cake ? They indicate that we want to print these exact wo rds to the screen. If we did no t put quo tatio n marks aro und these wo rds, they wo uld be interpreted as variables instead. The pro gram wo uld lo o k fo r the values given to these variables and tho se values wo uld be printed to the screen. Because cake Flavo r is a variable, there are no quo tatio n marks aro und it. We use plus signs (+) between the strings o f wo rds with quo tatio n marks and the cake Flavo r variable witho ut quo tatio n marks to indicate that the two will be co ncat e nat e d, and to make sure that o nly o ne string o f wo rds is printed to the screen. Every time we set the value o f a String, we put that value within quo tatio n marks (unless we are setting the value equal to a variable). The general syntax used is: St ring t he Variable Nam e = " t he t e xt yo u want t o print t o t he scre e n" ;

Variable Scope The sco pe o f a variable is essentially the bo undary fo r which the variable is valid. Because variable names o ften get used mo re than o nce, we need bo undaries to make it clear when the variable is applied. Variables are co nfined to the blo ck o f co de in which they are declared. The variable 's sco pe is limited to that blo ck o f co de. One way to visualize variable sco pe is to think o f class and metho d definitio ns as fences that co ntain variables. One end o f the fence is indicated by { and the o ther end o f the fence is indicated by } . No w think o f the variables as farm animals that live inside the fence (just play alo ng). There are three variables in the picture belo w--a Chicke n, a She e p, and a Fo x. The Chicke n is co nfined to the m e t ho d 1 fence and can't go anywhere else. The She e p is also co nfined. But the Fo x is able to go anywhere within the Farm Anim als class fence. This includes the m e t ho d 1 fence and the m e t ho d 2 fence. Therefo re, o ur Chicke n and She e p are no t safe. Variables that behave like the Fo x are kno wn as m e m be r variable s.

Illustratio n o f Variable Sco pe

No w take a lo o k at Cake .java. t o pLo cat io n, le f t Lo cat io n, and cake Flavo r are used tho ugho ut the Cake class. They are m e m be r variable s. They can be used within smaller blo cks o f co de (such as co nstructo rs). The variables t o p, le f t , and f lavo r, are declared within co nstructo rs o r metho ds. The sco pe o f these variables is limited to these blo cks o f co de. They are lo cal variable s. They can o nly be used within their lo cal blo ck o f co de. Let's try so me o f this stuff o ut. Bre ak the Cake class by using a variable o utside o f the variable's sco pe. Create a new Java file and type the fo llo wing into the Edito r:

CODE TO TYPE: import java.awt.*; public class BrokenCake { int topLocation; int leftLocation; String cakeFlavor; public BrokenCake(int top, int left) { topLocation = top; leftLocation = left; cakeFlavor = ""; } public BrokenCake(int top, int left, String flavor) { String lostVariable; lostVariable = "WONDERFUL"; topLocation = top; leftLocation = left; cakeFlavor = flavor; } public void frostCake(Color myColor, Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); g.drawString("I am a " + lostVariable + " Cake.", leftLocation + 50, top Location + 50); } }

When we Save/Co mpile this file (using the name Bro ke nCake .java), we get an erro r! OBSERVE: users/username/BrokenCake.java:29: Undefined variable: lostVariable g.drawString("I am a " + lostVariable + " Cake.", leftLocation + 50, topLocation + 50); ^ 1 error lo st Variable was declared in the Bro ke nCake co nstructo r, and it can o nly be used in the co de between { and } that define this co nstructo r. To make the value o f lo st Variable available to o ther metho ds, it must be declared as a member variable. Mo dify the Bro kenCake so urce file to lo o k like this:

CODE TO TYPE: import java.awt.*; public class BrokenCake { int topLocation; int leftLocation; String cakeFlavor; String lostVariable; public BrokenCake(int top, int left) { topLocation = top; leftLocation = left; cakeFlavor = ""; } public BrokenCake(int top, int left, String flavor) { lostVariable = "WONDERFUL"; topLocation = top; leftLocation = left; cakeFlavor = flavor; } public void frostCake(Color myColor, Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); g.drawString("I am a " + lostVariable + " Cake.", leftLocation + 50, top Location + 50); } }

Save/Co mpile. Success! This time Bro kenCake co mpiled witho ut erro rs. No w that we've given o ur lo st Variable the pro per sco pe by declaring it o utside o f a metho d, we can access its value fro m o ur f ro st Cake () metho d.

Accessing Variables from Another Class We can also access variables in o ne class fro m ano ther class. Let's try it, by creating ano ther applet that uses the Cake class. Create a new Java file and type the fo llo wing co de into the Edito r:

CODE TO TYPE: import java.applet.*; import java.awt.*; public class AnotherCakeApplet extends Applet { Cake myCake; public void init() { myCake = new Cake(0,0,"chocolate"); } public void paint(Graphics g) { g.setColor(Color.black); g.drawString(myCake.cakeFlavor, 10, 10); } }

Save/Co mpile this file as Ano therCakeApplet.java. To preview the new applet, type the fo llo wing into the Edito r belo w (make sure yo u create a New File in HTML Syntax Mo de): CODE TO TYPE:

Save this HTML file as Ano therCakeApplet.html. Then preview the file by clicking The Actio n Butto n in HTML Syntax Mo de. Here we accessed the cake Flavo r member variable fro m the Cake o bject m yCake . We used the do t no tatio n (m yCake .cake Flavo r) to access it. Do t no tatio n is used whenever we want to access an o bject o r pro perty that exists within ano ther o bject. Fo r example, to access my weight, I wo uld use the syntax sco t t .we ight . To access my perso nality I wo uld use the syntax sco t t .pe rso nalit y. Yo u have seen do t no tatio n used befo re with a metho d: m yCake .f ro st Cake (Co lo r.re d,g); So if I wanted to run 5 miles (and that's a big if!), I wo uld use the syntax sco t t .run(5 ). Yo u can't always access all o f the member variables in o ne class fro m ano ther class, tho ugh. We'll learn mo re abo ut that in the next lesso n. See yo u there! Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

More on Variables Setting Access Levels and Static Methods Setting Access Levels on Member Variables We build Java classes no t o nly fo r o ur o wn purpo ses, but fo r o ther pro grammers to use as well. Keep that in mind. Java's great po pularity and success stem fro m the fact that it lends itself to the creatio n o f reusable co de. In fact, yo u are go ing to co ntribute to its o ngo ing success as yo u write yo ur o wn pro grams. Po tential pro blems exist when making classes available to o ther pro grammers, tho ugh. Different variables o r metho ds may have been given the same name, o r a pro grammer might change the value o f a variable in a class and in do ing so , prevent the co de fro m wo rking co rrectly. Fo rtunately, we can pro tect o ur variables fro m o ther pro grammers' applicatio ns by co ntro lling access to them. We co ntro l access to variables by specifying that they are either privat e , package , pro t e ct e d, o r public (these are listed in o rder, fro m the mo st restrictive to the least restrictive variable). This table sho ws the access level permitted by each: Spe cif ie r class subclass package wo rld private

X

package

X

pro tected

X

X

X

public

X

X

X

X

X

private This is the mo st restrictive level o f access yo u can place o n a member variable (o r metho d as we'll see in the next lesso n.) It restricts access to the class that co ntains the member variable. Let's see ho w it wo rks using an example. Open o ur no w famo us Cake.java file in the Edito r. Add the red co de to yo ur existing co de by typing it into the Edito r:

CODE TO TYPE: import java.awt.*; public class CakeExample { int topLocation; int leftLocation; private String cakeFlavor; public CakeExample(int top, int left) { topLocation = top; leftLocation = left; cakeFlavor = "chocolate"; } public CakeExample(int top, int left, String flavor) { topLocation = top; leftLocation = left; cakeFlavor = flavor; } public void frostCake(Color myColor, Graphics g) { g.setColor(myColor); g.fillRect(leftLocation,topLocation, 50, 50); g.setColor(Color.black); g.drawString("I am a" + cakeFlavor + "Cake.", leftLocation + 50, topLoca tion + 50); } } Save/Co mpile this file using the name Cake Exam ple .java Of co urse, in o rder to test this co de we must use an applet that instantiates the CakeExample.java class. Open up the file Ano therCakeApplet.java that we saved in the last lesso n. Add the red co de to that file as sho wn: CODE TO TYPE: import java.applet.*; import java.awt.*; public class AnotherCakeApplet extends Applet { CakeExample myCake; public void init() { myCake = new CakeExample(0,0); } public void paint(Graphics g) { g.setColor(Color.black); g.drawString(myCake.cakeFlavor, 0, 0); myCake.frostCake(Color.black, g); } } Save/Co mpile this file as Ano therCakeApplet.java. As yo u may have guessed, we'll need an HTML file to run o ur Applet. Create a new HTML file and type the co de belo w into the Edito r:

CODE TO TYPE:

Be sure to save the HTML file using the name Ano t he rCake Apple t .ht m l. This might be a go o d time to do uble-check and make sure that yo u have bo th Ano t he rCake Apple t .java and Cake Exam ple .java saved in yo ur acco unt; we'll be using them in the upco ming examples. When yo u Preview Ano therCakeApplet.java with HTML yo u'll see that it didn't wo rk. What happened? Well, the first step in figuring that o ut is to lo o k at the co mpile e rro rs that were generated when yo u co mpiled this applet: OBSERVE: Co mpile erro rs

/users/username/AnotherCakeApplet.java:18: Variable cakeFlavor in class CakeExam ple not accessible from class AnotherCakeApplet. g.drawString(myCake.cakeFlavor, 0, 0); ^ 1 error

The erro r states that the variable cake Flavo r in class Cake Exam ple is no t acce ssible f ro m class Ano t he rCake Apple t . This is because we set the accessiblity o f cake Flavo r (in the CakeExample class) to privat e . A private variable is o nly accessible fro m the class in which it is declared. An erro r was generated because we tried to access this variable fro m Ano therCakeApplet. Private variables are used to help set values and are usually returned thro ugh a metho d. (We will discuss this mo re in the next lesso n.)

protected A pro t e ct e d variable is available to the class in which it is declared AND any subclass that extends that class. It is also available to any class that is in its package (we'll talk mo re abo ut packages in a bit). Take ano ther lo o k at the file Cake Exam ple .java. Try changing privat e St ring cake Flavo r to pro t e ct e d St ring cake Flavo r. Yo u do n't get an erro r message! That's because the Ano therCakeApplet and CakeExample classes are in the same package. We'll see examples o f this later, when we have learned mo re abo ut package s. Be sure to keep an eye o ut fo r tho se pro tected variables when yo u learn mo re abo ut packages!

package If yo u do no t declare a variable (o r metho d) as privat e , pro t e ct e d, o r public, then it is auto matically co nsidered a package variable. In fact, yo u canno t explicitly declare a package variable. A package variable is declared by leaving o ff all o ther declaratio ns. Think o f a package as, well, a package. It's a bo x that keeps related o bjects to gether. The items in a package are all related. They all have access to each o ther's member variables, while keeping them secret fro m classes that lie o utside o f the package. We'll see so me examples o f this later in the lesso n devo ted to packages.

public This access level makes all o f the members available to any class.

To make a variable public, we put the keywo rd public in fro nt o f it. Take ano ther lo o k at the file Cake Exam ple .java. Change privat e St ring cake Flavo r to public St ring cake Flavo r. Then Preview Ano therCakeApplet.java with HTML. This time it sho uld wo rk!

Static Variables (also called Class Variables) So , let's say we want to inst ant iat e three o bjects fro m the same class, fo r example, three different o bjects fro m the Cake class: m yCake , hisCake , and he rCake . Each o bject will have separate instances o f the member variables. Fo r example, o ne o f the member variables is cake Co lo r, which sto res the co lo r o f the cake. We can set the value o f cake Co lo r to three different co lo rs, then each o f the three cakes will be a different co lo r. If we change o ne o f the member variables (like m yCake .cake Co lo r), the o ther two member variables (hisCake .cake Co lo r and he rCake .cake Co lo r) will no t change. If we make cakeCo lo r a static variable, and we change o ne o f the member variables in o ne o f the o bjects, then all o f the variables will change. Let's try an example. First, we'll make a class that do esn't use st at ic and an applet that instatiates three Co lo rCake o bjects. We'll see that changing a member variable in o ne o bject do esn't affect the member variables in the o ther o bjects. Create a new Java file and type the fo llo wing co de into the Edito r: CODE TO TYPE: import java.awt.*; public class ColorCake { int topLocation; int leftLocation; Color cakeColor; public ColorCake(int top, int left, Color fillcolor) { topLocation = top; leftLocation = left; cakeColor = fillcolor; } public void frostCake(Graphics g) { g.setColor(cakeColor); g.fillRect(leftLocation, topLocation, 50, 50); } }

Save/Co mpile this file using the name Co lo rCake .java. We've declared a variable called cake Co lo r that is o f re f e re nce type Co lo r. Just like String, Co lo r is an o bject so meo ne else made fo r us. The variable cakeCo lo r will be set when the co nstructo r Co lo rCake is called in ano ther class and the Co lo r parameter f illCo lo r is set. No w we need an applet that instantiates co lo rCake. Let's call this applet Co lo rCake Apple t .java. Create ano ther new Java file and type the fo llo wing co de into the Edito r:

CODE TO TYPE: import java.applet.*; import java.awt.*; public class ColorCakeApplet extends Applet { ColorCake myCake, hisCake, herCake; public void init() { myCake = new ColorCake(0,0,Color.orange); hisCake = new ColorCake(0,75,Color.red); herCake = new ColorCake(0,150,Color.blue); } public void paint(Graphics g) { myCake.frostCake(g); hisCake.frostCake(g); herCake.frostCake(g); } }

Befo re co mpiling this file, let's make an HTML page so we can see the applet in actio n. Create a new HTML file and type the fo llo wing co de into the Edito r: CODE TO TYPE:

No w go back to Co lo rCakeApplet.java. Save/Co mpile the Java file using the name Co lo rCake Apple t .java, then Preview the applet when pro mpted. Yo ur applet displays an o range square, a re d square, and a blue square o n the screen. No w let's change the value o f the cakeCo lo r variable fo r myCake. We'll see that hisCake and herCake are no t effected by this change. Add the gre e n line o f co de belo w to Co lo rCakeApplet.java:

CODE TO TYPE: import java.applet.*; import java.awt.*; public class ColorCakeApplet extends Applet { ColorCake myCake, hisCake, herCake; public void init() { myCake = new ColorCake(0,0,Color.orange); hisCake = new ColorCake(0,75,Color.red); herCake = new ColorCake(0,150,Color.blue); } public void paint(Graphics g) { myCake.cakeColor = Color.green; myCake.frostCake(g); hisCake.frostCake(g); herCake.frostCake(g); } }

Save/Co mpile the file again, then preview it using HTML. Yo ur applet displays a gre e n square, a re d square, and a blue square o n the screen. We changed the myCake o bject so that it wo uld be gre e n. All o f the o ther o bjects remained the same. No w let's make cakeCo lo r a static member variable. Open up the o riginal Co lo rCake .java file. Add the wo rd static to the cakeCo lo r declaratio n: CODE TO TYPE: import java.awt.*; public class ColorCake { int topLocation; int leftLocation; static Color cakeColor; public ColorCake(int top, int left, Color fillcolor) { topLocation = top; leftLocation = left; cakeColor = fillcolor; } public void frostCake(Graphics g) { g.setColor(cakeColor); g.fillRect(leftLocation, topLocation, 50, 50); } }

Save/Co mpile this file. No w o pen the Co lo rCake Apple t .java file again. Save/Co mpile Co lo rCake Apple t .java and preview the applet when pro mpted. What happened? All three squares are gre e n no w! This is the result o f making the cake Flavo r variable

st at ic. When we changed the value o f cakeCo lo r fo r the myCake o bject, the co lo r o f the hisCake o bject and herCake o bject changed to o . Think o f "static" as so mething that ties instances o f the class to gether. Changing a static value in o ne o bject changes the value in all o bjects. A class can access the value o f a st at icvariable witho ut inst ant iat ing the o bject. In the abo ve example, we can use the statement Co lo rCake .cake Co lo r, access the value held in the cakeCo lo r variable, and change its value witho ut instantiating myCake, o r hisCake, o r herCake. Static variables are also caled class variable s because the value can be accessed thro ugh a class instead o f an o bject.

Final Variables We can also declare a variable to be f inal. Declaring a variable as f inal makes it co nstant. Once it's set, it canno t be changed by anybo dy. Let's build o n o ur last example to see this to o l in actio n. Once again, o pen up the file Co lo rCake .java. Add the wo rd final to the cakeCo lo r declaratio n: CODE TO TYPE: import java.awt.*; public class ColorCake { int topLocation; int leftLocation; static final Color cakeColor = Color.black; public ColorCake(int top, int left, Color fillcolor) { topLocation = top; leftLocation = left; cakeColor = fillcolor; } public void frostCake(Graphics g) { g.setColor(cakeColor); g.fillRect(leftLocation, topLocation, 50, 50); } }

Save/Co mpile this file using the name Co lo rCake .java. We get an erro r: OBSERVE: /users/username/ColorCake.java:12: Can't assign a value to a final variable: cakeColor cakeColor = fillcolor; ^ 1 error

What happened? We defined the cakeCo lo r variable as f inal, meaning its value canno t change. Once this value is set, it is permanent. So , when we tried to modify the value o f cakeCo lo r, the co mpiler gave us an erro r. Remember that fo r future reference. Phew! We are do ne with variables fo r no w, but we'll revisit these co ncepts tho ugho ut the co urse. Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Methods Methods Methods Make T hings Happen We've used m e t ho ds thro ugho ut the co urse. In this lesso n, we'll go o ver metho ds in greater detail, and we'll also investigate parameters, returning values, using static metho ds, and pro tecting metho ds. Let's take a lo o k at so me o f the ways we've used metho ds so far. Open up the latest versio n o f Cake .java. OBSERVE: import java.awt.*; public class Cake { int topLocation; int leftLocation; String cakeFlavor; public Cake(int top, int left) { topLocation = top; leftLocation = left; } public Cake(int top, int left, String flavor) { topLocation = top; leftLocation = left; cakeFlavor = flavor; } public void frostCake(Color myColor, Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); g.drawString("I am a" + cakeFlavor + "Cake.", leftLocation + 50, topLoca tion + 50); } } All o f the co de in green defines a m e t ho d. We've discussed these metho ds in previo us lesso ns, so they're pro bably familiar to yo u. The Cake metho d is a special metho d called a co nstructo r. A co nstructo r can be lo cated easily because it has the same name as the class. Co nstructo rs are used to "co nstruct" an o bject fro m a class. They allo w us to set different pro perties when we instantiate an o bject fro m a class. We have also used the f ro st Cake () metho d extensively. We used it to create a co lo red square and print wo rds to the screen. Whenever a metho d is defined, pare nt he se s are used. The parentheses co ntain the param e t e rs o f the metho d. A parameter is a co ntainer that will ho ld the values passed to the metho d when it is called. The f ro st Cake () metho d requires two parameters. Each parameter is seperated by a co mma. The two parameters o f the f ro st Cake () metho d are myCo lo r and g: OBSERVE: public void frostCake(Color myColor, Graphics g) {

Yo u can define a metho d using as many parameters as yo u like, o r yo u do n't have to use parameters at all if yo u do n't need them. But yo u must always use parentheses, even if there are no parameters within them. If f ro st Cake () didn't have any parameters, it wo uld be defined like this: OBSERVE: public void frostCake() {

The statements that make up the metho d are placed in between o pen and clo sed curly brackets -- { and } .

Returning Values In the last lesso n we saw that we co uld use variables to get values fro m the class. We can also get values fro m metho ds. Have yo u no ticed that when we define metho ds (with the exceptio n o f co nstructo rs), we put the keywo rd vo id in fro nt o f the metho d name? We used vo id in the f ro st Cake () definitio n: OBSERVE: public void frostCake(Color myColor, Graphics g) {

Void indicates that the metho d do es no t return any value to us; it o nly executes the statements within the curly brackets. But what if we want to retrieve a value fro m a metho d? Suppo se we want to give a metho d two wo rds, use the metho d to co mbine the two wo rds, then retrieve this new wo rd? Let's try it! Add the fo llo wing metho d to the Cake.java file:

CODE TO TYPE: Cake.java import java.awt.*; public class Cake { int topLocation; int leftLocation; String cakeFlavor; public Cake(int top, int left) { topLocation = top; leftLocation = left; } public Cake(int top, int left, String flavor) { topLocation = top; leftLocation = left; cakeFlavor = flavor; } public void frostCake(Color myColor, Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); g.drawString("I am a" + cakeFlavor + "Cake.", leftLocation + 50, topLoca tion + 50); } public String combine(String firstString, String secondString){ String combinedString = firstString + secondString; return combinedString; } } Befo re yo u Save/Co mpile this, no tice we used St ring when we defined the co m bine () metho d where we wo uld have no rmally used vo id. When we call the co m bine () metho d, it will re t urn a string! We can access this string with the variable co m bine dSt ring. Save/Co mpile the file Cake .java. No w let's make an applet that uses this class and o ur new metho d. We'll need an HTML page to preview o ur applet, so let's go ahead and make that no w. Create a new file in HTML Syntax Mo de, type the co de belo w into the Edito r: CODE TO TYPE:

Save this as Ano therCakeApplet.html Open up the file Ano therCakeApplet.java into the Edito r. In Co deRunner, mo dify the so urce co de so that it lo o ks e xact ly like this:

CODE TO TYPE: Ano therCakeApplet.java import java.applet.*; import java.awt.*; public class AnotherCakeApplet extends Applet { Cake myCake; public void init() { myCake = new Cake(0,0); } public void paint(Graphics g) { String cakeType = myCake.combine("Angel","Food"); g.setColor(Color.black); g.drawString(cakeType, 10, 10); } }

Save/Co mpile this file using the name Ano therCakeApplet.java, then Preview the applet when pro mpted. Yo u'll see the wo rds Ange lFo o d printed to the screen. The co m bine () metho d was called in Ano therCakeApplet.java: OBSERVE: String cakeType = myCake.combine("Angel","Food");

The co m bine () metho d returns the value sto red in co m bine dSt ring. The returned value will be sto red in cake T ype when the metho d is called. In this example, the co m bine () metho d returns the value " Ange lFo o d" , so that's the value sto red in the cake T ype variable. This is why the wo rd Ange lFo o d is printed to the screen.

Passing Values as Parameters Parameters are really just variables. They are used to sto re values which are passed to the metho d when it is called. In the co m bine () metho d, the parameter f irst St ring is used to sto re " Ange l" and the parameter se co ndSt ring is used to sto re " Fo o d" . No tice that we must declare what t ype o f data the parameter will sto re. In this case, each parameter will sto re a St ring. The sco pe o f a parameter is limited to its metho d. So in o ur example, firstString and seco ndString have no meaning o utside o f the statements within the co m bine () metho d.

Setting Access Levels on Methods In the last lesso n yo u learned ho w to set access levels fo r member variables. We can also set access levels fo r metho ds. They can be public, private, pro tected, o r package: -No access mo difier (package access): the default access level, visible to the package o nly. -Public mo difier: visible to any o ther Java class in the wo rld. -Private mo difier: visible to the current class o nly. -Pro tected mo difier: visible to sub-class o f the current class, and any class in the same package as the current class. These access levels wo rk in exactly the same way as they do fo r variables. So , if we set the access level fo r the co m bine () metho d to private in the Cake class, we co uld no t have called it in o ur Ano therCakeApplet class. Instead, we wo uld be limited to using the co m bine () metho d lo cally, within the Cake class. Try changing the access level o n the co m bine () metho d to determine if any level o ther than public wo rks.

Static Methods (Class Methods)

Static metho ds are extermely useful in Java. The static keywo rd has ro ughly the same effect o n metho ds as it did o n variables. If a metho d is declared as static, then yo u can call this metho d witho ut instantiating an o bject fro m the class in which it resides. Let's change o ur last example so that the co m bine () metho d is static. Open up the file Cake .java into the Co deRunner Edito r, and change the co de as sho wn: CODE TO TYPE: import java.awt.*; public class Cake { int topLocation; int leftLocation; String cakeFlavor; public Cake(int top, int left) { topLocation = top; leftLocation = left; } public Cake(int top, int left, String flavor) { topLocation = top; leftLocation = left; cakeFlavor = flavor; } public void frostCake(Color myColor, Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); g.drawString("I am a" + cakeFlavor + "Cake.", leftLocation + 50, topLoca tion + 50); } public static String combine(String firstString, String secondString){ String combinedString = firstString + secondString; return combinedString; } } Save/Co mpile this file using the name Cake .java. No w switch the file so that Ano t he rCake Apple t .java is displayed in the Edito r. Change Ano therCakeApplet.java so that it lo o ks like this:

CODE TO TYPE: import java.applet.*; import java.awt.*; public class AnotherCakeApplet extends Applet { //

Cake myCake; notice this is commented out. public void init() { myCake = new Cake(0,0);

//

} public void paint(Graphics g) { String cakeType = Cake.combine("Angel","Food"); g.setColor(Color.black); g.drawString(cakeType, 10, 10); } }

Yo u can see that we've co m m e nt e d o ut the lines that instantiate the m yCake o bject fro m the Cake class, and that we reference the Cake class directly when we call the co m bine metho d.

Note

Co m m e nt ing o ut a line o f co de means that line wo n't be reco gnized by the pro gram. We've do ne it here in Java using two back-slashes (//). We'll go o ver this in detail later, so do n't wo rry abo ut it fo r no w.

Save/Co mpile this file using the name Ano therCakeApplet.java, and preview the file when pro mpted. It sho uld wo rk the same as befo re, except this time we did no t instantiate an o bject. So why wo uld we want to use static metho ds anyway? It do esn't always make sense to instantiate an o bject when yo u want to use a metho d. Fo r instance, Java supplies us with a Mat h o bject that has metho ds to perfo rm mathematical o peratio ns, like Mat h.sqrt () (the square ro o t functio n). We do n't have to instantiate any Math o bjects to use these metho ds since they are static. We simply call Mat h.sqrt () just like we called Cake .co m bine () abo ve. In o ur example we just changed a local variable and returned it. We sho uld keep in mind that st at ic m e t ho ds can o nly wo rk wit h st at ic variable s. Befo re yo u leave this lesso n, try experimenting o n yo ur o wn with this: Change the Cake class abo ve so that combinedString is a member variable (no t just defined fo r the metho d). Make sure that co m bine () is still a Static Metho d. The idea is to see that the class wo n't co mpile unless the co mbined String variable is defined as static. Try using the Math o bject. Make a call to Mat h.sqrt () in Ano therCakeApplet.java and print o ut the result. Try taking the square ro o t o f 9 like this Mat h.sqrt (9 ); (set it to a variable then print that variable o ut). Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

The Java API Packages and APIs Organizing Functionality Have yo u ever been to an o pen street market? Yo u kno w, the type that has lo ts o f little sto res that each specializes in selling a certain type o f pro duct?

The butcher sho p sells meats and po ultry, the market sells fruits and vegetables, and the flo wer sho p sells flo wers. Well, in the same way that these markets have o rganized into specialty sto res, we can o rganize o ur Java classes into packages—gro ups o f related classes with a specialized functio nality.

Packages: Pre-Made T ools Let's jump right in and create o ur o wn package—later we'll see ho w this applies to the Java API. First, we need to create a new fo lder in o ur acco unt. Right-click anywhere in the File Bro wser and cho o se Ne w Fo lde r. Name yo ur new fo lder f ruit (all lo wercase). Next, we want to create a co uple o f classes fo r o ur new package. Create the two new Java so urce files sho wn in the examples belo w. Add the fo llo wing to what will be named AnOrange .java: CODE TO TYPE: package fruit; public class AnOrange { public AnOrange (java.awt.Graphics g) { g.setColor(java.awt.Color.orange); g.fillOval(5, 5, 50, 50); } } The o ther Java file will be named Pe ar.java. Add the fo llo wing co de to this file: CODE TO TYPE: package fruit; public class Pear { public Pear (java.awt.Graphics g) { g.setColor(java.awt.Color.green); g.fillOval(110, 5, 40, 75); g.fillOval(105, 30, 50, 50); } } Save and co mpile these files. Make sure yo u save them to the new fruit directo ry. We've created a co uple o f new Classes that represent fruits. But we can't preview them because they're not applets. So , befo re we wo rry abo ut ho w these classes wo rk, let's go ahead and make a Java Applet that instantiates o ur new "fruit" o bjects. Be sure to save this Java Applet in yo ur ho me directo ry (no t in the fruit

instantiates o ur new "fruit" o bjects. Be sure to save this Java Applet in yo ur ho me directo ry (no t in the fruit directo ry, but in the directo ry where yo u created the fruit directo ry). Add Fruit yApple t .java to yo ur Edito r as sho wn belo w: CODE TO TYPE: import java.applet.*; import java.awt.*; public class FruityApplet extends Applet { public void paint(Graphics g) { fruit.AnOrange anOrangeObject = new fruit.AnOrange(g); fruit.Pear aPearObject = new fruit.Pear(g); } } In o ur fruit classes, we did so mething new in o ur "fruit" so urce files, we defined a package statement. It sho uld lo o k so mething like this: OBSERVE: package fruit; Later, when o ur FruityApplet instantiated so me Orange and Pear o bjects, we to ld the JVM to lo o k fo r tho se classes in the f ruit package by typing this co de. It lo o ked like this: OBSERVE: fruit.AnOrange anOrangeObject = new fruit.AnOrange(g); The package name we defined has exactly the same name as the directo ry where we sto red these fruit class definitio ns. We can use these classes thro ugh a package reference because they were each defined as part of the fruit package (package fruit;). We kno w that if we put a bunch o f classes into a directo ry, we can define all o f tho se classes as parts o f a package. But when we use tho se classes, why do we always have to type f ruit . befo re the class name? Well, let's see what happens when we do n't. Change Fruit yApple t .java to lo o k like this: CODE TO TYPE: import java.applet.*; import java.awt.*; public class FruityApplet extends Applet { public void paint(Graphics g) { fruit.AnOrange anOrangeObject = new fruit.AnOrange(g); fruit.Pear aPearObject = new fruit.Pear(g); } } When we Save/Co mpile, we get an erro r:

OBSERVE: /users/username/FruityApplet.java:12: Class AnOrange not found in type declarati on. AnOrange anOrangeObject = new AnOrange(g); ^ /users/username/FruityApplet.java:12: Class AnOrange not found in type declarati on. AnOrange anOrangeObject = new AnOrange(g); ^ 2 errors By no w yo u may have no ticed that the Java Co mpiler so metimes gives cryptic messages. This particular erro r is telling us that the co mpiler didn't kno w where to find the "AnOrange" class that we created, so it co uldn't po ssibly co mpile o ur FruityApplet. It might seem like the co mpiler has given us the same erro r twice--it didn't. The co mpiler first co mplained abo ut o ur initial reference to the AnOrange class ("AnOrange anOrange Obje ct "), and then it co mplained abo ut o ur reference to the AnOrange constructor ("ne w AnOrange (g)") in the seco nd erro r. Yo u also might have no ticed that the co mpiler did no t co mplain abo ut the Pear class and o bject co nstructo r. Well, this may seem kind o f lazy, but the co mpiler will o ften sto p co mpiling o nce it has fo und 2 erro rs. Hey, do n't ask me...I wo uldn't have made it that way! :) We can tell the co mpiler where to find classes in the f ruit package by adding "f ruit ." befo re any reference to o ur fruit package's classes, but there sho uld be an easier way, do n't yo u think? Fo rtunately, there is. Change Fruit yApple t .java to lo o k like this: CODE TO TYPE: import java.applet.*; import java.awt.*; import fruit.*; public class FruityApplet extends Applet { public void paint(Graphics g) { AnOrange anOrangeObject = new AnOrange(g); Pear aPearObject = new Pear(g); } } Save/Co mpile. By adding that im po rt statement, we no lo nger have to type "fruit." befo re referencing classes in o ur fruit package. The impo rt statement allo ws us to tell the JVM to search thro ugh that package auto matically, whenever a class definitio n is referenced--basically we are giving the co mpiler a hint.

Using the Java API Earlier in the co urse, I mentio ned that there are already a number o f existing Java Classes that we can use to develo p o ur o wn pro grams. The Java API (sho rt fo r "Application Programming Interface") is a large co llectio n o f these pre-made classes o rganize d int o package s. If we extend o ur earlier analo gy co mparing an o pen street market to Java Packages, we might think o f an API as being the city blo ck where tho se sto res are lo cated. Generally, an API is a co lle ct io n o f package s, each with so me specialized purpo se. The Java API is such a co llectio n. The Java API is almo st always the basis fo r Java so ftware and o ther Java APIs, such as Oracle's JavaMail API, which helps in develo ping EMail related so ftware in Java. That is, the JavaMail API uses (and o ften extends) many o f the classes co ntained in the Java API. To view the Java API, visit http://do cs.o racle.co m/javase/7/do cs/api/ When we want to bo rro w a class fro m the Java API, we start by telling the JVM where, that is, in which package to lo o k fo r the class. Edit the co de in FruityApplet.java to lo o k like this:

CODE TO TYPE: // we're taking out the import java.applet.*; statement import java.awt.*; import fruit.*; public class FruityApplet extends Applet { public void paint(Graphics g) { AnOrange anOrangeObject = new AnOrange(g); Pear aPearObject = new Pear(g); } } Save/Co mpile. Who o ps...we get an erro r! Check o ut the erro r fro m abo ve so urce file: OBSERVE: /users/username/FruityApplet.java:5: Superclass Applet of class FruityApplet not found. public class FruityApplet extends Applet { ^ 1 error Yup--o ur class requires the java.apple t .Apple t class fro m the java.apple t package. When the co mpiler do esn't kno w where to find java.apple t .Apple t , it gives us erro rs. Edit the co de in FruityApplet.java to lo o k like this: CODE TO TYPE: import java.awt.*; import fruit.*; public class FruityApplet extends java.applet.Applet { public void paint(Graphics g) { AnOrange anOrangeObject = new AnOrange(g); Pear aPearObject = new Pear(g); } } No big surprise here. We gave the co mpiler an explicit reference to the location o f the java.applet.Applet class, so it knew where to lo o k. No w let's undo what we just did and see what happens. Edit the co de in FruityApplet.java so it lo o ks like this: CODE TO TYPE: import java.applet.Applet; import java.awt.*; import fruit.*; public class FruityApplet extends Applet { public void paint(Graphics g) { AnOrange anOrangeObject = new AnOrange(g); Pear aPearObject = new Pear(g); } } Save/Co mpile. That's interesting. We can impo rt o nly o ne class fro m a package. We're able to do it in o ur example because we kno w that we o nly need the java.apple t .Apple t class fro m the java.apple t package. No rmally we'd just say im po rt java.apple t .* So why wo uld we do it any o ther way? Well, we've do ne so me

pretty in-depth research and discussio n at OST o n this subject. Basically, neither syntax is significantly better than the o ther. Just be aware that yo u can import classes using either syntax.

Where does it all come from? Yo u may have no ticed that the names o f the packages we've discussed here are defined using dot notation (i.e. so mething.so methingelse.whatever). In the case o f packages, the do ts represent directories. Fo r instance, "im po rt f ruit .*;" po ints to classes in the "fruit" directo ry. (Tho se classes MUST de f ine themselves as being part o f the f ruit package .) In the same way, "im po rt java.apple t .*" po ints to tho se classes sto red in a directo ry named apple t , which in turn is sto red in a directo ry named java. Fo r tho se o f us familiar with Micro so ft Windo ws filesystems (and do n't panic if yo u aren't), it wo uld lo o k like this: "C:\java\apple t \*" (in UNIX, it wo uld lo o k like /java/apple t /*.) OBSERVE: import java.applet.*; This snippet o f co de tells o ur pro gram to lo o k in the directo ry named java with the sub-directory apple t fo r any class. The co mpiler also always imports a co uple o f extra things. The co mpiler always aut o m at ically lo o ks fo r classes in the same directo ry as o ur class (as lo ng as they do n't belo ng to ano ther package!) Check it o ut: OBSERVE: import *; Additio nally, the co mpiler always auto matically imports o ne o f the Java API packages: java.lang. This package has classes that are at the core o f the Java language: OBSERVE: import java.lang.*;

Where in our filesystem are these Java API directories? We can see that the Java API directo ries aren't in o ur OST directo ry. We kno w that o ur fruit directo ry and package are in the same directo ry as o ur FruityApplet, so the JVM will start lo o king in the same directo ry as the class we're running (in this case o ur FruityApplet.) But , there's definitely no "java/lang" directo ry in o ur acco unt, so where's the co mpiler finding that? The Co mpiler and JVM kno w by default where to find the directo ry structure co ntaining the Java API (yo u tell the JVM when yo u install it, but that's a co nversatio n fo r ano ther co urse). In any case, a functio ning JVM (such as the o ne in o ur bro wser) has to be able to lo cate the packages co ntained in the Java API.

What classes are available in the Java API? Javaso ft, Oracle's Java Organizatio n pro vides the list o f all default (available to everybo dy) packages in several fo rmats via the web. To see the co mplete documentation fo r these packages, click here. So far, so go o d. No w yo u can yo u create yo ur o wn Java Packages/API's fo r use in yo ur pro grams, and import packages fro m the Java API (o r fo r that matter any package) into yo ur pro grams. Yo u've co me a lo ng way! I'll see yo u in the next lesso n where we'll start explo ring the Java API! Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Control Structures: Loops Loops In previo us lesso ns, we co ded things "o ne at a time". Java also allo ws us to do things in lo o ps. Lo o ps help yo u to build mo re efficient co de, and will allo w yo u to execute blo cks o f co de repeatedly. In this lesso n, we'll learn ho w to use lo o ps to auto mate co de.

Your First Loop Let's build o ur first lo o p! We will do this by first creating co de that do es not use a lo o p so that we can understand ho w lo o ps can be be used to simplify co de. Create a new so urce file named Lo o ps.java. CODE TO TYPE: import java.applet.*; import java.awt.*; public class Loops extends Applet { public void paint(Graphics g) { int leftLocation=10; int topLocation=10; g.drawString("the g.drawString("the g.drawString("the g.drawString("the g.drawString("the

value value value value value

is is is is is

1", 2", 3", 4", 5",

leftLocation, leftLocation, leftLocation, leftLocation, leftLocation,

topLocation+10); topLocation+20); topLocation+30); topLocation+40); topLocation+50);

} }

Save/Co mpile. Here we have created so me simple co de to that is used to display five strings. The strings are very similar. The o nly difference is the value that is displayed, and the lo cat io n at which they are displayed. Each time the string is printed, a new value is adde d t o t he t o pLo cat io n variable so that the values will be printed 10 pixels belo w the previo us string. Run this co de to see fo r yo urself what happens. Of co urse, first we'll need to create an HTML file to display o ur applet. CODE TO TYPE:

Save this as Lo o ps.html. Preview yo ur applet. Yo u sho uld see five strings, each string displayed directly belo w the previo us o ne. As simple as the abo ve co de is, we can use lo o ps to reduce the amo unt o f typing. Mo dify Lo o ps.java so that it lo o ks like the file belo w.

CODE TO TYPE: import java.applet.*; import java.awt.*; public class Loops extends Applet { public int int int

void paint(Graphics g) { leftLocation=10; topLocation=10; count=1;

while (count y

returns

Do It

To p

Less T han or Equal T o = y

returns

Do It

To p

Unary Operators Unary Ope rat o rs o perate o n o nly o ne value.

Negation This o perato r can o nly be used with numbers o r variables o f numerical type. It makes a number negative. It wo rks like this: -x

x

-x

Do It

To p

Increment ++ This o perato r can o nly be used with numbers o r variables o f numerical type. It takes a value and adds o ne (1) to it. It wo rks like this: x++ This o perato r do es the same thing as x = x + 1;. In English: " x be co m e s x + 1" .

x

x++

Do It

To p

Decrement -This o perato r can o nly be used with numbers o r variables o f numerical type. It takes a value and subtracts o ne (1) fro m it. It wo rks like this: x--

x

x--

Do It

To p All things co nsidered, o perato rs aren't so to ugh. But it's impo rtant fo r yo u to kno w to the specific implementatio n o f each o f them in Java befo re yo u go o n. Reread the o perato r explanatio ns until yo u're familiar with them. Befo re lo ng, they'll co me to yo u naturally. Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Data-Typing and Conversion Converting Data T ypes So far the o nly thing we've printed to the screen are String values. In this lesso n, we'll learn why that's the case. We'll also learn ho w to co nvert variable data types into o ther variable types.

Converting Integers to Strings Let's create a new applet class to experiment with and learn abo ut data co nversio n. Create a new Java so urce file just like the fo llo wing: CODE TO TYPE: import java.applet.*; import java.awt.*; public class DataTypeConverter extends Applet { private int xPosition = 125; public void paint(Graphics g) { g.drawString(xPosition, 10, 10); } } Save/Co mpile this as DataTypeCo nverter.java. When yo u co mpile, yo u get an erro r. Take a lo o k: OBSERVE: /users/kendellw/DataTypeConverter.java:9: Incompatible type for method. Can't convert int to java.text.AttributedCharacterIterator. g.drawString(xPosition, 10, 10); ^ 1 error

At t ribut e dCharact e rIt e rat o r. What is that? Well, imagine yo u have several co ntainers that ho ld bo xes: a square co ntainer that ho lds a square bo x, a triangular co ntainer that ho lds a triangular bo x, and a circular co ntainer that ho lds a circular bo x. Then imagine that we have a new bo x that we want to put into each o f these co ntainers. To fit o ur new bo x into the square bo x, we need to fo ld the new bo x into a square. Befo re we can fit that same new bo x into the triangular co ntainer, we need to unfo ld the bo x and pro ceed to fo ld the bo x into a triangular shape, right? (Just go with it.) Java data types wo rk in much the same way. By lo o king at the API (Applicatio n Pro gramming Interface--a a list o f all o f the functio ns and o bjects available in Java), yo u'll see that the java.awt.Graphics.drawSt ring() metho d requires that we supply the value we want printed to the screen in the fo rm o f a String data type. Ho wever, the value we want printed, xPo sit io n, is o f type int . Therefo re, befo re we can print o ut the value o f xPo sitio n with the drawSt ring() metho d, we must convert the int data type to a String data type. In the previo us example, when we didn't co nvert xPo sitio n, the AttributedCharacterIterato r class realized that the value passed was no t o f data type String, so it gave us an erro r. Update yo ur DataTypeCo nverter.java so urce file as sho wn:

CODE TO TYPE: import java.applet.*; import java.awt.*; public class DataTypeConverter extends Applet { private int xPosition = 125; private String xPositionString; public void paint(Graphics g) { xPositionString = Integer.toString(xPosition); g.drawString(xPositionString, 10, 10); } } Save/Co mpile. Create an html file to view yo ur applet. Pre vie w yo ur apple t . No w the applet wo rks. To make the example applet wo rk, we needed to convert the int value o f xPo sitio n to a String data type be f o re we passed it as an argument to the drawSt ring() metho d. So no w we kno w that if a metho d receives a parameter that is no t o f an acceptable type, the metho d wo n't wo rk. This is really inco nvenient if the variables we have are no t co mpatible with the metho ds we need to use. To so lve this pro blem, we co nvert the data type into so mething the metho d can use. To co nvert integer data types, we must use a metho d that has been pro vided to us within the java.lang.Integer class. As we mo ve o n, yo u'll see that the java.lang.Integer class pro vide metho ds fo r co nverting integers into o ther data types, and the java.lang package pro vides classes fo r co nverting o ther primitive data types as well.

Using Data T ypes Let's try using vario us o perato rs o n a few String data types. Mo dify yo ur DataTypeCo nverter.java so urce file as sho wn: CODE TO TYPE: import java.applet.*; import java.awt.*; public class DataTypeConverter extends Applet { private int xPosition = 125; private String somethingToAdd = "5.12345"; public void paint(Graphics g) { g.drawString(somethingToAdd + Integer.toString(xPosition), 10, 1 0); } } Save/Co mpile. Preview the Applet. When yo u preview the co de, yo u'll see that rather than arithmetically adding o ur two "numbers" to gether (which wo uld have resulted in 130 .12345, right?), it co mbined o ur two values as o ne big String (5 .1234 5 125). Adding these two String values to gether is called concatenation. This is unique to the String class. If yo u "add" two String data types to gether, the co ncatenatio n o f the two Strings being added to gether is returned in the fo rm o f a new String. This type o f concatenation is unique String class.

Note

Yo u co uld also use g.drawSt ring(so m e t hingT o Add + xPo sit io n, 10 , 10 ) with the same result, because using the plus sign auto matically co nverts primitives to Strings if they fo llo w a String value.

Suppo se we actually want to add o ur two String data types to gether numerically. That is, we actually want to figure o ut the sum o f the two Strings. What wo uld we need to do ? The Strings wo uld need to be co nverted to a primitive data type that co uld be added to gether. We'd need to co nvert the String variable so m e t hingT o Add into a numeric value. Ho wever, if we check the Java API do cumentatio n, yo u'll no tice that there is no java.lang.St ring.t o Flo at () metho d. So ho w wo uld we do this? Mo dify yo ur DataTypeCo nverter.java so urce file as sho wn:

CODE TO TYPE: import java.applet.*; import java.awt.*; public class DataTypeConverter extends Applet { private int xPosition = 125; private String somethingToAdd = "5.12345"; public void paint(Graphics g) { double xPositionDoubleValue = new Integer(xPosition).doubleValue (); double somethingToAddDoubleValue = new Double(somethingToAdd).do ubleValue(); double answerDoubleValue = somethingToAddDoubleValue + xPosition DoubleValue; g.drawString("Before Conversion: " + Integer.toString(xPosition) + " + " + somethingToAdd + " = " + Integer.toString(xPosition) + somethi ngToAdd, 10, 10); g.drawString("After Data Conversion: " + new Double(xPositionDou bleValue).toString() + " + " + new Double(somethingToAddDoubleValue).toString() + " = " + new Double(answerDoubleValue).toString(), 10, 50); } } Once again, Save/Co mpile yo ur applet and Preview it. If yo u take a clo ser lo o k at the co de we've added, yo u'll see that we used double data types to sto re o ur data. This makes sense because we'll use decimal places when we finish adding o ur values to gether. But the data types we started with are o f type int and St ring. So , what do we need to do in o rder to wo rk with these two different data types? Right! We need to co nvert o ur data fro m int and String types into do uble values. Go o d call! To acco mplish this task, we first instantiate a ne w Do uble o bje ct fro m the java.lang.Do uble class. If yo u take a lo o k at the Java API, yo u'll see that the java.lang.Do uble class pro vides a co nstructo r that takes in a String o bject, and creates a Do uble o bject that sto res the String data as do uble data. Once the new Do uble o bject is created, we're able to use the do uble Value () metho d to return o ur String data as a do uble value. Once we've arit hm e t ically adde d o ur new do uble value s, we can then print them to o ur applet by co nve rt ing them to a St ring value . Be aware, java.lang.Do uble o bjects are no t the same as a do uble primitive! Rather, the java.lang.Do uble class was written to wo rk with do uble primitives. All these classes (java.lang.Do uble, java.lang.Integer, java.lang.Flo at, and so o n) were created to pro vide a wrappe r classs fo r primitive data types. These wrapper classes pro vide data type co nversio n and o ther metho ds fo r primitive data types. So , in o ur example, when we instantiated o ur java.lang.Do uble o bjects, we used the metho ds pro vided in the wrapper class to o utput the primitive data types these classes "wrap." In the last example, we cho se to use do uble values because we wanted to perserve the decimal places in o ur so lutio n. We co uld have cho sen float value, which also suppo rts decimal places just as easily, but witho ut as much precisio n. Let's try it and see what happens! Mo dify yo ur DataTypeCo nverter.java so urce belo w file by adding the blue co de as sho wn:

CODE TO TYPE: Mo dify DataTypeCo nverter.java import java.applet.*; import java.awt.*; public class DataTypeConverter extends Applet { private int xPosition = 125; private String somethingToAdd = "5.12345"; public void paint(Graphics g) { float xPositionFloatValue = new Integer(xPosition).floatValue(); float somethingToAddFloatValue = new Float(somethingToAdd).float Value(); float answerFloatValue = somethingToAddFloatValue + xPositionFlo atValue; g.drawString("Before Conversion: " + Integer.toString(xPosition) + " + " + somethingToAdd + " = " + Integer.toString(xPosition) + somethi ngToAdd, 10, 10); g.drawString("After Data Conversion: " + new Float(xPositionFloa tValue).toString() + " + " + new Float(somethingToAddFloatValue).toString() + " = " + new Float(answerFloatValue).toString(), 10, 50); } } Save/Co mpile and Preview. It lo o ks identical to what we did befo re right? Well, pretty much, but if yo u lo o k clo sely at the results, yo u'll no tice that the flo at values didn't add up co rrectly. In fact, the result is .0 0 0 0 1 o ff o f the mathematically co rrect result. We kno w that the flo at data type do esn't sto re numbers with as much accuracy as the do uble data type do es. When the JVM perfo rms a mathematical o peratio n, the answer is returned acco rding to the number o f significant digits, as defined by that data type--it ro unds the answer. So metimes, we do n't get a precise answer when using inappro priate data types, so it's extremely impo rtant to cho o se the co rrect data type fo r the info rmatio n we need to sto re. Ho wever, since a do uble data type is mo re accurate, it takes up mo re space in co mputer memo ry than a flo at. We have to take into co nsideratio n no t o nly the precisio n o f the data we need, but also ho w much o f the system's reso urces we're using.

Note

If we had co ded this example pro perly, instead o f creating an example full o f inco rrect data types, xPo sit io n and so m e t hingT o Add wo uld have been defined fro m the beginning as do uble data types because bo th values wo uld eventually be co nverted to do uble values befo re we co uld wo rk with them.

More Static Methods--'Sticky Code' If yo u've been paying clo se attentio n (and I kno w yo u have), yo u kno w that when we were co nverting Integer data types to o ther data types, we didn't have to instantiate a new Integer o bject. Why is this yo u ask? Well, instead o f instantiating a new Integer o bject, we were able to call java.lang.Int e ge r.t o St ring() directly, and pass o ur Integer value to it as a parameter. So metimes classes define st at ic m e t ho ds that do n't require any info rmatio n abo ut specific instantiated o bjects o f that class type. That is, static metho ds are available glo bally to any class that kno ws where to find them, regardless o f whether the class co ntaining the metho d has been instantiated as an o bject. In o ur example, we didn't have to instantiate a new Integer o bject to use the static t o St ring() metho d that the Integer class defines. Let's try an example to help yo u understand the co ncept o f static metho ds a bit better. Mo dify yo ur DataTypeCo nverter.java so urce file as sho wn:

CODE TO TYPE: import java.applet.*; import java.awt.*; public class DataTypeConverter extends Applet { private int xPosition = 125; private String somethingToAdd = "5.12345"; public void paint(Graphics g) { float xPositionFloatValue = new Integer(xPosition).floatValue(); float somethingToAddFloatValue = new Float(somethingToAdd).float Value(); float answerFloatValue = somethingToAddFloatValue + xPositionFlo atValue; g.drawString("Before Conversion: " + Integer.toString(xPosition) + " + " + somethingToAdd + " = " + Integer.toString(xPosition) + somethi ngToAdd, 10, 10); g.drawString("After Data Conversion: " + Float.toString(xPositio nFloatValue) + " + " + Float.toString(somethingToAddFloatValue) + " = " + Float.toStr ing(answerFloatValue), 10, 50); } } Save/Co mpile and Preview. Take a lo o k at the co de. Pretty co o l, huh? No w, let's try to co nvert between a St ring and f lo at data types. Mo dify yo ur DataTypeCo nverter.java so urce file again: CODE TO TYPE: import java.applet.*; import java.awt.*; public class DataTypeConverter extends Applet { private int xPosition = 125; private String somethingToAdd = "5.12345"; public void paint(Graphics g) { float xPositionFloatValue = new Integer(xPosition).floatValue(); float somethingToAddFloatValue = Float.floatValue(somethingToAdd ); float answerFloatValue = somethingToAddFloatValue + xPositionFlo atValue; g.drawString("Before Conversion: " + Integer.toString(xPosition) + " + " + somethingToAdd + " = " + Integer.toString(xPosition) + somethi ngToAdd, 10, 10); g.drawString("After Data Conversion: " + Float.toString(xPositio nFloatValue) + " + " + Float.toString(somethingToAddFloatValue) + " = " + Float.toStr ing(answerFloatValue), 10, 50); } } Save/Co mpile and preview this applet. In this example, we're trying to co nvert so methingTo Add and xPo sitio n into flo at values, then arithmetically add them to gether, and finally print o ut the results. Take a clo ser lo o k at the so urce co de. If o ur earlier examples are an indicatio n, this change seems like it sho uld wo rk. But, when yo u co mpile and preview this time aro und, yo u ge t an e rro r! Check it o ut:

OBSERVE: /users/kendellw/DataTypeConverter.java:10: Wrong number of arguments in method. float somethingToAddFloatValue = Float.floatValue(somethingToAdd); ^ 1 error There are two reaso ns fo r this erro r. If yo u check the Java API do cumentatio n, yo u'll see that the java.lang.Flo at class do esn't define a metho d named f lo at Value () that suppo rts St ring dat a t ype param e t e rs. In fact, the f lo at Value () metho d do esn't take any parameters at all. Let's fix that and try so mething a little different. Mo dify yo ur DataTypeCo nverter.java so urce file as sho wn: CODE TO TYPE: import java.applet.*; import java.awt.*; public class DataTypeConverter extends Applet { private int xPosition = 125; private String somethingToAdd = "5.12345"; public void paint(Graphics g) { float xPositionFloatValue = new Integer(xPosition).floatValue(); float somethingToAddFloatValue = Float.floatValue(); float answerFloatValue = somethingToAddFloatValue + xPositionFlo atValue; g.drawString("Before Conversion: " + Integer.toString(xPosition) + " + " + somethingToAdd + " = " + Integer.toString(xPosition) + somethi ngToAdd, 10, 10); g.drawString("After Data Conversion: " + Float.toString(xPositio nFloatValue) + " + " + Float.toString(somethingToAddFloatValue) + " = " + Float.toStr ing(answerFloatValue), 10, 50); } } Save/Co mpile again. When we try to co mpile, we still get an erro r! Take a lo o k: OBSERVE: /users/kendellw/DataTypeConverter.java:10: Can't make static reference to method float floatValue() in class java.lang.Floa t. float somethingToAddFloatValue = Float.floatValue(); ^ 1 error There's that wo rd "static" again, which brings us to the seco nd reaso n that the Java co mpiler returns an erro r: when the Java co mpiler tells us that we "can't make reference" to so mething, it means that the thing we tried to reference didn't have the keyword "static" applied to it in the so urce co de. We can verify this in o ur example by checking the Java API do cumentatio n. We see that Flo at . f lo at Value () metho d is no t a static method. While we're lo o king thro ugh the API do cumentatio n, we can also see that the Flo at .t o St ring() metho d is a static metho d.

So, when to convert a static reference to a method? By getting friendly and familiar with the Java API! The mo re yo u pro gram in Java, the mo re yo u'll access the Java API do cumentatio n fo r answers to yo ur burning questio ns. Eventually, yo u'll remember the API metho ds that yo u use mo st o ften. Familiarity with the API makes a Java pro grammer much mo re efficient. Let's get back to o ur example and change the mo dified DataTypeCo nverter.java to fix the erro rs that were returned. We want o ur co de to turn the String variable so methingTo Add into a flo at value. Instead o f trying to

use a static metho d to acco mplish this task, let's create a new Flo at o bject. Take a lo o k at the Java API do cumentatio n. The java.lang.Flo at class has a co nstructo r that takes in a String o bject and co nverts the String o bject into a flo at value. After the Flo at o bject is created, we can use the f lo at Value () metho d to get the flo at value o ut o f the Flo at o bject. Take a few minutes to figure o ut what yo u need to do to fix the erro rs. No w edit the DataTypeCo nverter.java so urce file as sho wn belo w: CODE TO TYPE: import java.applet.*; import java.awt.*; public class DataTypeConverter extends Applet { private int xPosition = 125; private String somethingToAdd = "5.12345"; public void paint(Graphics g) { float xPositionFloatValue = new Integer(xPosition).floatValue(); float somethingToAddFloatValue = new Float(somethingToAdd).float Value(); float answerFloatValue = somethingToAddFloatValue + xPositionFlo atValue; g.drawString("Before Conversion: " + Integer.toString(xPosition) + " + " + somethingToAdd + " = " + Integer.toString(xPosition) + somethi ngToAdd, 10, 10); g.drawString("After Data Conversion: " + Float.toString(xPositio nFloatValue) + " + " + Float.toString(somethingToAddFloatValue) + " = " + Float.toStr ing(answerFloatValue), 10, 50); } } Did yo ur so lutio n match up with mine? In the next lesso n, we'll go o ver Arrays; a class that allo ws us to sto re mo re than o ne piece o f data. See yo u there. Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Object Arrays Converting Between Data T ypes In this lesso n we'll learn ho w to use arrays; variables that can ho ld multiple values o r Objects.

T he Array An array is like a filing cabinate o r a ro lo dex; a place where yo u o rganize and sto re data. Fo r example, here's a sample array called names (it already co ntains a few names):

An array called nam e s: The beauty o f an array is in the way we access the slo ts within it. Fo r instance, if we wanted to kno w what name was in the third slo t o f this array, we wo uld ask fo r: OBSERVE: names[3] The value returned wo uld be "To ny." If we wanted to change the name in the fo urth slo t to Jo sh, we wo uld do this: OBSERVE: names[4] = Josh;

The array then beco mes: Of co urse, the array abo ve is o nly a graphical representatio n o f an array, but it's the picture I want yo u to have in yo ur mind when we discuss arrays.

Creating Arrays in Java Let's create a new applet we can use to play with so me Arrays, and at the same time, we'll go ahead and instantiate a new Array. Create a new Java so urce file. Feel free to substitute the names o f yo ur friends:

CODE TO TYPE: import java.applet.*; import java.awt.*; public class UsingArrays extends Applet { public String[] names = new String[7]; public void init() { } public void paint(Graphics g) { names[0] = "scott"; names[1] = "kendell"; names[2] = "Trish"; names[3] = "Tony"; names[4] = "Mike"; names[5] = "Debra"; names[6] = "Curt"; } } We initialized a ne w variable : nam e s. We did no t instantiate any new o bjects. By applying tho se [] (brackets) to o ur data type declaration, we to ld the JVM that we're creating a ne w array t o ho ld St ring value s. In the case o f this array, we're giving it se ve n place ho lde rs, o therwise kno wn as indices. Next, in the paint () metho d, we filled o ur array with so me St ring values. In each case, we pro vided a different index fo r each value. Our indices never go t larger than 6 . But we started o ur indices with 0 (zero ), and we used all o f o ur placeholders. In Java, all array indices start with 0 , so the last index that we can use wo uld be: OBSERVE: number of placeholders - 1 Get it? Co o l. Okay, no w let's do so mething with o ur new array. Think abo ut which type o f co ntro l structure do yo u think wo uld take the best advantage o f a sequential set of numbers. Add the fo r lo o p (in bo ld) to UsingArrays:

CODE TO TYPE: import java.applet.*; import java.awt.*; public class UsingArrays extends Applet { public String[] names = new String[7]; public void init() { } public void paint(Graphics g) { names[0] = "scott"; names[1] = "kendell"; names[2] = "Trish"; names[3] = "Tony"; names[4] = "Mike"; names[5] = "Debra"; names[6] = "Curt"; for (int x = 0; x < 7; x++) { g.drawString(names[x],10,20 * x + 10); } } } We're familar with loops, so this co de may make sense already. All we did was create a for loop that iterates fro m 0 (o ur lo west index) to 6 (o ne le ss t han 7 ). On each iteration, the Graphics.drawSt ring() metho d paints the value sto red at that specific index. We also adjust e d o ur Y Co o rdinat e to make sure we didn't paint o ur values o ne o n to p o f the o ther. Save/Co mpile this as UsingArrays.java, and create an HTML page to preview it in, if yo u want to see this in actio n befo re we mo ve o n.

Something Different Let's refine what we've already do ne. Co ntinue to feel free to substitute the names o f yo ur friends: CODE TO TYPE: import java.applet.*; import java.awt.*; public class UsingArrays extends Applet { public String[] names = {"scott", "kendell", "Trish", "Tony", "Mike", "Debra ", "Curt"}; public void init() { } public void paint(Graphics g) { for (int x = 0; x < 7; x++) { g.drawString(names[x],10,20 * x + 10); } } } Save/Co mpile and Preview UsingArrays.java. In this example we instantiated o ur String values in a different way: using a list. A Java list is a set o f data, separated within {} curly brackets. Our array takes each element o n this list, and places it in o ne o f o ur array's placeho lders. The list syntax is so metimes mo re co nvenient than assigning values in the vario us po sitio ns o f o ur array individually--but no t always. Yo u'll kno w which to use when yo u need it. Use the fo rce. But o ne day, when yo u're writing yo ur o wn pro grams in Java, yo u'll pro bably have a situatio n where yo u do n't kno w exactly ho w many indices yo ur array will have. When that day co mes, yo u will have Java arrays at yo ur

dispo sal, which allo w yo u to query their size. Make the fo llo wing edit to UsingArrays: CODE TO TYPE: import java.applet.*; import java.awt.*; public class UsingArrays extends Applet { public String[] names = {"scott", "kendell", "Trish", "Tony", "Mike", "Debra ", "Curt"}; public void init() { } public void paint(Graphics g) { for (int x = 0; x < names.length; x++) { g.drawString(names[x],10,20 * x + 10); } } } Save/Co mpile and Preview. When Java creates an array, it actually instantiates an Array Object. One o f the variable values in this Array Object is le ngt h: a value representing the num be r o f indice s in the array. So , if we do n't kno w the length o f an array, we can always query that array to find o ut. Alright then, o nward! Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Advanced Object Orientation Part I - OO Design Advanced Object Orientation Part I - OO Design Getting 'Object Oriented' Suppo se we were making a Java Applet that represented a Waitress. Of co urse, o ur Waitress is go ing to serve fo o d to o ur custo mers. In o ur case, o ur Waitress will be serving Cake and Pie. I think it wo uld make the mo st sense fo r us to create Java Objects fo r the Cakes and Pies that we serve to o ur custo mers. Let's start by mo difying go o d o ld Cake.java: CODE TO TYPE: import java.awt.*; public class Cake { int topLocation; int leftLocation; Color myColor; public Cake(int top, int left, Color thisColor) { topLocation = top; leftLocation = left; myColor = thisColor; } public void bake(Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); } } Save/Co mpile this, keeping the name Cake.java Create a new Java file fo r the Pie Class as sho wn: CODE TO TYPE: import java.awt.*; public class Pie { int topLocation; int leftLocation; Color myColor; public Pie(int top, int left, Color thisColor) { topLocation = top; leftLocation = left; myColor = thisColor; } public void bake(Graphics g) { g.setColor(myColor); g.fillOval(leftLocation, topLocation, 50, 50); g.setColor(Color.black); } }

Save/Co mpile this as, yo u guessed it, Pie.java. I do n't think there's anything abo ut these new o bjects that will catch yo u by surprise, but did yo u no tice that bo th o ur Cake and Pie o bjects have a bake metho d? Let's create a Waitress Applet to bake o ur Cakes and Pies. Create a new Java file and add the fo llo wing co de: CODE TO TYPE: import java.applet.*; import java.awt.*; public class Waitress extends Applet { Cake myCake; Pie myPie; public void paint(Graphics g) { // instantiate the objects, giving a position and Color myCake = new Cake(0, 0, Color.yellow); myPie = new Pie(0, 100, Color.blue); // call the bake() in the Cake and Pie objects myCake.bake(g); myPie.bake(g); } } Save/Co mpile Waitress.java and create an HTML page fo r it. Try it o ut--yo u'll see that o ur "cake" and "pie" were painted to the applet. Let's think abo ut o ur o bjects and o ur Waitress Applet fo r a mo ment. Our o bjects (Cake and Pie) each have a metho d named bake () that takes o ne parameter--a java.awt.Graphics Object. And, o f co urse, real Cake and Pie are bo t h f o o ds. Yo u kno w, if we apply Java's Object Orientatio n capabilities to o ur applet, it wo uld make sense fo r bo th o f o ur "Food Objects" to extend a Fo o d class. So let's create a Fo o d class, and change o ur Cake and Pie o bjects to make them extend Fo o d. They'll bo th be Food o bjects, right? Go ahead and create the Fo o d Class: CODE TO TYPE: import java.awt.*; public class Food { public Food() { } public void bake(Graphics g) { } } Mo dify the Cake class as sho wn:

CODE TO TYPE: import java.awt.*; public class Cake extends Food { int topLocation; int leftLocation; Color myColor; public Cake(int top, int left, Color thisColor) { topLocation = top; leftLocation = left; myColor = thisColor; } public void bake(Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); } } Mo dify the Pie class as sho wn: CODE TO TYPE: import java.awt.*; public class Pie extends Food { int topLocation; int leftLocation; Color myColor; public Pie(int top, int left, Color thisColor) { topLocation = top; leftLocation = left; myColor = thisColor; } public void bake(Graphics g) { g.setColor(myColor); g.fillOval(leftLocation, topLocation, 50, 50); g.setColor(Color.black); } } Make sure that yo u've Save/Co mpiled all three files. By extending Food we make sure that even if o ur Cake and Pie o bjects do n't define a bake () metho d, they will definitely inherit the bake () metho d fro m the Fo o d class. To get a better understanding o f ho w that's useful, let's call o n a co uple o f o ld friends, the loop and the array, and see ho w they might help o ur Waitress. Edit the Waitress Applet, like this:

CODE TO TYPE: import java.applet.*; import java.awt.*; public class Waitress extends Applet { public Food[] myMeal = new Food[2]; public void paint(Graphics g) { // instantiate the objects, giving a position and Color, // store them in the myMeal array myMeal[0] = new Cake(0, 0, Color.yellow); myMeal[1] = new Pie(0, 100, Color.blue); // call the bake() in ALL of the Cake and Pie objects for (int x = 0; x < myMeal.length; x++) { myMeal[x].bake(g); } } } When we Save/Co mpile this, we see that o ur Waitress Applet do es exactly the same thing as it did befo re. Let's take a lo o k: Instead o f defining variables fo r o ur Cake and Pie o bjects, the f irst thing we did was create an Array o f Fo o d o bje ct s. Our Cake and Pie o bject extend Fo o d. Altho ugh they add so me o f their o wn features specific to being a Cake o r a Pie, they are indeed still Fo o d o bjects. Since they are Fo o d o bjects, when we instantiate o ur Cake and Pie o bjects, we can sto re them in an Array o f Fo o d o bje ct s. Since we put o ur Cake and Pie o bjects into an Array o f Food o bjects, we were able to use a For Loop to iterate thro ugh each item and call their bake () metho ds. Bo th o ur Cake and Pie classes defined the bake () metho d (over-riding the bake() in Food.) We put all kinds o f Fo o d o bjects into o ur Array. But because o ur Fo o d class defined the bake () metho d, when we actually called the bake () metho d, we didn't have to tell the JVM what kind o f Fo o d we were se rving, just that it was a Fo o d o bject (in a Fo o d Array). The JVM called the bake () metho d in o ur Cake and Pie o bject, witho ut co nsidering the types of Food they were.

What now? Go o d questio n. So far we've learned so me neat tricks to use with Object-Oriented Design (OO). Next, we'll wo rk with a fairly co mplicated example to learn abo ut Abstract Classes. Make sure yo u save all o f t he f ile s f ro m t his le sso n f o r use in t he ne xt le sso n! See yo u there... Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Advanced Object Orientation Part II - Abstracts Advanced Object Orientation - Abstracts T hinking in the Abstract Let's start this lesso n by testing the limits o f Object-Oriented Design. First we'll create a new type o f Food. Create the Do nut class as sho wn: CODE TO TYPE: import java.awt.*; public class Donut extends Food { public Donut() { } } Save/Co mpile it. Okay, no w let's mo dify o ur Waitress to bake () a Do nut. Edit the Waitress Applet so it lo o ks like this: CODE TO EDIT: import java.applet.*; import java.awt.*; public class Waitress extends Applet { public Food[] myMeal = new Food[3]; public void paint(Graphics g) { // instantiate the objects, giving a position and Color, // store them in the myMeal array myMeal[0] = new Cake(0, 0, Color.yellow); myMeal[1] = new Pie(0, 100, Color.blue); myMeal[2] = new Donut(); // call the bake() in ALL of the Cake and Pie objects for (int x = 0; x < myMeal.length; x++) { myMeal[x].bake(g); } } } With that co de, we incre ase d t he size o f o ur Array, and then inst ant iat e d a Do nut o bject and sto red it. Adding mo re Food o bjects isn't so to ugh, huh? But, ho ld o n--there is o ne pro blem. Our Do nut class did not over-ride (define) the Food class's bake () metho d. When o ur Waitress called o ur Do nut's bake () metho d, it actually called the Fo o d class's bake () metho d that Do nut inherited. Fo o d do esn't do anything with the bake () metho d. Our Object-Oriented design ensures that when we call the bake () metho d o f a Fo o d o bject, we do n't run into pro blems. That's go o d, but we also want to require Fo o d o bje ct s to implement certain metho ds. Let's mo dify the Fo o d class:

CODE TO TYPE: import java.awt.*; public abstract class Food { public Food() { } public abstract void bake(Graphics g); } Save/Co mpile this new abstract class, then let's experiment with o ur Do nut. Open and Co mpile the Do nut class: OPEN AND COMPILE: import java.awt.*; public class Donut extends Food { public Donut() { } } Yo u might have no ticed that o ur Fo o d.bake () metho d no lo nger defines a body (it no lo nger has {} curly brackets.) Because o f the changes we made to Food, we get an erro r when we co mpile the Do nut class no w. Here's the erro r we get fro m o ur example: OBSERVE: /users/username/Donut.java:1: class Donut must be declared abstract. It does not define void bake(java.awt.Graphics) from class Food. public class Donut extends Food { ^ 1 error If we think back to o ur Food class, we placed the keywo rd abst ract in o ur class definitio n. Take a lo o k: OBSERVE: import java.awt.*; public abstract class Food { public Food() { } public abstract void bake(Graphics g); } Here's a quick example o f the way this co ncept o f abstract may wo rk in real life. Imagine so meo ne asked us to describe a candle. We might describe it as so me wax with a wick sticking o ut o f it that yo u can ignite so that it gives o ff light. That pretty much describes any candle, but we kno w there are many different kinds o f candles, with vario us types o f wax, wicks, scents, co lo rs, and o ther qualities. When we described the candle, we described it in the abstract sense; it was simply a generalizatio n o f the features o f any candle.

The Java keywo rd abstract wo rks in essentially the same way. When we use the abstract keywo rd befo re a m e t ho d, we're telling the co mpiler that a class t hat e xt e nds t his class MUST de f ine t his m e t ho d. Let's fix o ur Do nut class. Mo dify the Do nut class co de so it lo o ks like this: CODE TO TYPE: import java.awt.*; public class Donut extends Food { public Donut() { } public void bake(Graphics g) { g.setColor(Color.pink); g.fillOval(0, 100, 50, 50); g.setColor(Color.gray); g.fillOval(15, 115, 20, 20); } } Declaring o ur Fo o d class abstract fo rces o ur Do nut class to define the bake () metho d with its o wn instructio ns. As a result, o ur Waitress Applet can have so me assurance that this class is go ing to behave like a Food.

Not Entirely Abstract Still, no t all metho ds in an abst ract class have to be abst ract . Let's test this claim. Mo dify the Fo o d class as sho wn: CODE TO TYPE: import java.awt.*; public abstract class Food { public Food() { } public abstract void bake(Graphics g); public String whatAmI() { return "I am a Food"; } } We just added a metho d to o ur abst ract Fo o d class. But we did no t make this new metho d abst ract . So it stands to reaso n that this metho d wo uld be inherited and usable by all sub-classes, right? Let's find o ut using o ur Waitress Applet. Mo dify the Waitress Applet as sho wn:

CODE TO TYPE: import java.applet.*; import java.awt.*; public class Waitress extends Applet { public Food[] myMeal = new Food[3]; public void paint(Graphics g) { // instantiate the objects, giving a position and Color, // store them in the myMeal array myMeal[0] = new Cake(0, 0, Color.yellow); myMeal[1] = new Pie(0, 100, Color.blue); myMeal[2] = new Donut(); // call the bake() in ALL of the Cake and Pie objects for (int x = 0; x < myMeal.length; x++) { myMeal[x].bake(g); } g.drawString(myMeal[2].whatAmI(), 125, 125); } } Sure eno ugh, o ur Do nut class inherits the what Am I() metho d fro m Food. When we paint the results to the applet, "I am a Fo o d" is painted to the screen. No t all o f the metho ds in o ur abstract classes have to be abstract! If we do n't declare a metho d abst ract , the sub-class will inherit the functio nality o f that metho d.

Variables - Abstract or Not No t. When yo u think abo ut it, there's no reaso n to declare abstract variables. If yo u define them no rmally in the abstract class, then they will be defined in the sub-classes auto matically and wo n't need additio nal initializatio n (not to mention, you'll write less code.) If all o f this abstract business isn't perfectly clear to yo u just yet, do n't wo rry. Yo u'll be expo sed to this co ncept again later and beco me mo re co mfo rtable with it. In the next lesso n we're go ing to explo re Interfaces. Interfaces wo rk a lo t like abstract classes, but have their o wn capabilities. See yo u there! Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

Advanced Object Orientation - Interfaces Advanced Object Orientation - Interfaces Multiple Inheritance So , within the Waitress Applet and Fo o d o bjects we created in the last lesso n, we created an Abstract Food class to require its sub-classes (Cake, Pie, and Do nut) to define the bake () metho d. That way, o ur Waitress can bake all kinds o f Fo o d o bjects using simplified co de. But wait! There's a pro blem with o ur mo del o f a Waitress. After o ur custo mers are finished eating their Cake, Pie, and Do nuts, they want o ur Waitress to bring them a their Bill (invo ice). Right no w o ur Waitress o nly kno ws ho w to deal with Food o bjects. But a Bill is not a Food. It's a Payment o bject. Our Bill is a Payment o bject. So naturally, o ur Bill o bject sho uld extend a Payment class. Let's create an Abstract Payment class that describes what o ur Payment o bjects sho uld be like. Create the Payment class: CODE TO TYPE: import java.awt.*; public abstract class Payment { public abstract void printItem(Graphics g); } Pretty straight fo rward, right? We define an Abst ract class that requires its sub-classes to implement the print It e m () metho d. Let's go ahead and create o ur Bill class: CODE TO TYPE: import java.awt.*; public class Bill extends Payment { public Bill () { //a constructor that doesn't do anything } public void printItem(Graphics g) { g.setColor(Color.white); g.fillRect(100, 100, 50, 50); g.setColor(Color.black); g.drawLine(110, 110, 140, 110); g.drawLine(110, 120, 140, 120); g.drawLine(110, 130, 140, 130); } } When we Save/Co mpile this, we do n't get any erro rs, but we still have a pro blem. We can't simply sto re o ur Bill o bject in o ur Waitress's Food Array because it's no t a sub-class o f Food. Wo uldn't it be nice if o ur Bill class co uld extend bo th Payment AND Food? Let's try it. Mo dify the Bill class so it lo o ks like this:

CODE TO TYPE: import java.awt.*; public class Bill extends Payment, Food { public Bill () { //a constructor that doesn't do anything } public void printItem(Graphics g) { g.setColor(Color.white); g.fillRect(100, 100, 50, 50); g.setColor(Color.black); g.drawLine(110, 110, 140, 110); g.drawLine(110, 120, 140, 120); g.drawLine(110, 130, 140, 130); } } We learned that a class can o nly e xt e nd o ne class. No t surprisingly, we go t an erro r when we Save/Co mpiled. Check o ut the erro r fro m abo ve example: OBSERVE: /users/username/Bill.java:3: Multiple inheritance is not supported. public class Bill extends Payment, Food { ^ /users/username/Bill.java:3: '{' expected. public class Bill extends Payment, Food { ^ 2 errors Well, we've demo nstrated that we can't extend mo re than o ne class at a time. So , ho w do we handle this situatio n? It wo uld be nice to sto re o ur Fo o d and Payment o bjects in o ne big array. That way, o ur Waitress co uld de live r all o f o ur object types at o nce. Let's co nsider the reaso n we can't extend multiple data types. Suppo se we added a non-abstract metho d named de live r() to bo th o ur Fo o d and Payment classes. Do n't actually mo dify yo ur Food and Payment classes (it wo n't wo rk anyway). Just check o ut the updated Fo o d class: OBSERVE: import java.awt.*; public abstract class Food { public Food() { } public abstract void bake(Graphics g); public void deliver(Graphics g) { g.fillRect(100, 100, 50, 50); } } Take a lo o k at the updated Payment class:

OBSERVE: import java.awt.*; public abstract class Payment { public abstract void printItem(Graphics g); public void deliver(Graphics g) { g.fillOval(100, 100, 50, 50); } } In these imaginary classes, we created a new metho d: de live r(). No w, let's imagine what wo uld happen if we were allo wed to extend bo th o f these classes. Lo o k o ver the Bill class: OBSERVE: import java.awt.*; public class Bill extends Payment, Food { public Bill () { //a constructor that doesn't do anything } public void printItem(Graphics g) { deliver(g); g.setColor(Color.white); g.fillRect(100, 100, 50, 50); g.setColor(Color.black); g.drawLine(110, 110, 140, 110); g.drawLine(110, 120, 140, 120); g.drawLine(110, 130, 140, 130); } } Think abo ut this situatio n. Suppo se o ur Bill class co uld extend bo th Food and Payment. What wo uld happen if Bill called the de live r() metho d? By extending bo th Food and Payment, o ur Bill class inhe rit s Food.deliver() (paints a rectangle) and Paym e nt .de live r() (paints a Circle). So , when o ur Bill class calls this inherited metho d, do es it paint a Rectangle, a Circle, bo th, o r neither? In C++, pro grammers have to co nsider this po tential pro blem because C++ classes can have multiple inheritance. In Java, that pro blem can't exist because a class can no t e xt e nd m o re t han o ne class.

Using Interfaces for Multiple-Inheritance Style Data-T yping It's co nvenient that we do n't have to wo rry abo ut multiple-inheritance issues in Java. But multiple-inheritance o ffers so me advantages that we might like to use. It wo uld be great if o ur Food and Payment classes were co mpletely Abstract, that is, if they defined o nly Abstract metho ds and no metho ds were actually inherited by sub-classes. We need J ava Interfaces. Interfaces are essentially pure abstract classes. In fact, we wo n't even have to use the Abstract keywo rd, because the co mpiler already kno ws that they're Abstract. Let's experiment with a Java interface. Create the DeliverableItem Interface as sho wn:

CODE TO TYPE: import java.awt.*; public interface DeliverableItem { public void deliver(Graphics g); } Save/Co mpile that as DeliverableItem.java (use the same file-naming scheme that we used fo r all o ther types o f Java classes.) No w, let's mo dify o ur Bill class to take advantage o f this new interface. Revise yo ur co de fo r the Bill class so it lo o ks like this: CODE TO TYPE: import java.awt.*; public class Bill extends Payment implements DeliverableItem { public Bill () { //a constructor that doesn't do anything } public void printItem(Graphics g) { g.setColor(Color.white); g.fillRect(100, 100, 50, 50); g.setColor(Color.black); g.drawLine(110, 110, 140, 110); g.drawLine(110, 120, 140, 120); g.drawLine(110, 130, 140, 130); } } When we Save/Co mpile, we get an erro r: OBSERVE: /users/username/Bill.java:4: class Bill must be declared abstract. It does not d efine void deliver(java.awt.Graphics) from interface DeliverableItem. public class Bill extends Payment implements DeliverableItem { ^ 1 error This erro r resembles an erro r we go t in the last lesso n. DeliverableItem is really no different fro m an Abstract Class, e xce pt that an Interface can o nly de f ine abst ract m e t ho ds (there's no danger o f inherited metho ds interfering with o ne ano ther.) By implementing one or more Interface(s), we can create o bjects that can functio n as multiple data types. In o ur case, we didn't define the de live r() metho d that o ur Interface required, so we go t an erro r. Let's fix o ur Bill class:

CODE TO TYPE: import java.awt.*; public class Bill extends Payment implements DeliverableItem { public Bill () { //a constructor that doesn't do anything } public void printItem(Graphics g) { g.setColor(Color.white); g.fillRect(100, 100, 50, 50); g.setColor(Color.black); g.drawLine(110, 110, 140, 110); g.drawLine(110, 120, 140, 120); g.drawLine(110, 130, 140, 130); } public void deliver(Graphics g) { printItem(g); } }

Using Interfaces to Help our Waitress Let's see ho w using Interfaces might help o ur Waitress Applet. Mo dify the Cake, Pie, and Do nut classes as sho wn, so that they all implement DeliverableItem: CODE TO TYPE: import java.awt.*; public class Cake extends Food implements DeliverableItem { int topLocation; int leftLocation; Color myColor; public Cake(int top, int left, Color thisColor) { topLocation = top; leftLocation = left; myColor = thisColor; } public void bake(Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); } public void deliver(Graphics g) { bake(g); } } No w mo dify the Pie class:

CODE TO TYPE: import java.awt.*; public class Pie extends Food implements DeliverableItem { int topLocation; int leftLocation; Color myColor; public Pie(int top, int left, Color thisColor) { topLocation = top; leftLocation = left; myColor = thisColor; } public void bake(Graphics g) { g.setColor(myColor); g.fillOval(leftLocation, topLocation, 50, 50); g.setColor(Color.black); } public void deliver(Graphics g) { bake(g); } } And mo dify the Do nut class: CODE TO TYPE: import java.awt.*; public class Donut extends Food implements DeliverableItem { public Donut() { } public void bake(Graphics g) { g.setColor(Color.pink); g.fillOval(0, 100, 50, 50); g.setColor(Color.gray); g.fillOval(15, 115, 20, 20); } public void deliver(Graphics g) { bake(g); } } It go es witho ut saying that yo u sho uld Save/Co mpile all o f these files. Okay, no w o ur Cake, Pie, Do nut, and Bill classes all implement DeliverableItem. Let's see ho w o ur Waitress can make use o f this new Object-Oriented Design! Mo dify the Waitress Applet as sho wn:

CODE TO TYPE: import java.applet.*; import java.awt.*; public class Waitress extends Applet { public DeliverableItem[] myMeal = new DeliverableItem[4]; public void paint(Graphics g) { // instantiate the objects, giving a position and Color, // store them in the myMeal array myMeal[0] myMeal[1] myMeal[2] myMeal[3]

= = = =

new new new new

Cake(0, 0, Color.yellow); Pie(0, 100, Color.blue); Donut(); Bill();

// call the bake() in ALL of the Cake and Pie objects for (int x = 0; x < myMeal.length; x++) { myMeal[x].deliver(g); } } } When we Save/Co mpile, we see that o ur Bill has been delivered alo ng with o ur Cake, Pie, and Do nut Food o bjects. Because all o f the items implement the De live rable It e m interface, we can sto re them all in a De live rable It e m Array.

Inheritance with Interfaces In o ur previo us example, we to o k each o f o ur individual o bje ct s and, by implementing DeliverableItem, we enabled them all to be used as DeliverableItem objects. But we did no t necessarily guarant e e that all Fo o ds were DeliverableItems. Suppo se that we decided we wanted all Fo o d o bjects to be DeliverableItems. Here's ho w we might do that. Mo dify the Fo o d Class as sho wn: CODE TO TYPE: import java.awt.*; public abstract class Food implements DeliverableItem { public Food() { } public abstract void bake(Graphics g); public void deliver(Graphics g) { bake(g); } } We changed o ur Abstract Food class so that it im ple m e nt s De live rable It e m . We also implemented the non-Abstract de live r() metho d. Because the de live r() metho d is not Abstract, we kno w it will be inherited by all sub-classes of Food. Mo dify yo ur co de as sho wn belo w to see why this is useful:

CODE TO TYPE: import java.awt.*; public class Cake extends Food { int topLocation; int leftLocation; Color myColor; public Cake(int top, int left, Color thisColor) { topLocation = top; leftLocation = left; myColor = thisColor; } public void bake(Graphics g) { g.setColor(myColor); g.fillRect(leftLocation, topLocation, 50, 50); g.setColor(Color.black); } } Mo dify the Pie Class: CODE TO TYPE: import java.awt.*; public class Pie extends Food { int topLocation; int leftLocation; Color myColor; public Pie(int top, int left, Color thisColor) { topLocation = top; leftLocation = left; myColor = thisColor; } public void bake(Graphics g) { g.setColor(myColor); g.fillOval(leftLocation, topLocation, 50, 50); g.setColor(Color.black); } } Mo dify the Do nut class:

CODE TO TYPE: import java.awt.*; public class Donut extends Food { public Donut() { } public void bake(Graphics g) { g.setColor(Color.pink); g.fillOval(0, 100, 50, 50); g.setColor(Color.gray); g.fillOval(15, 115, 20, 20); } } Yo u may have no ticed that o ur Cake, Pie, and Do nut classes are in the o riginal state they were in befo re we ever started wo rking with Interfaces. Do yo u suppo se this means that they no lo nger im ple m e nt De live rable It e m ? When we think abo ut ho w inheritance wo rks, we no tice that o ur Cake, Pie, and Do nut classes inhe rit ALL pro pe rt ie s o f Fo o d. Because we inherited the Fo o d.de live r() metho d, we do n't need to explictly implement a de live r() metho d in each o f o ur Cake, Pie, and Do nut classes. There is a po tential do wn-side to using inheritance in this way. No w, no matter what we do , all Fo o d o bje ct s are also De live rable It e m s. In o ur example, this is just fine. But it's po ssible that we might no t always want multiple data-typing. Fo rtunately, we always have the o ptio n o f implementing in individual classes available, just like we did in the previo us example. So after yo ur final pro ject, that's a wrap fo r this lesso n and the co urse! In later co urses, we're go ing to do even mo re with Interfaces. Interfaces and Abstract classes beco me extremely useful as Java pro grams beco me mo re and mo re co mplicated. Go o d jo b! It's been great having yo u here. Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.