Lesson One - Introduction There is only one way that you can learn to program in a new language and that is by doing it. You can read as many books as you like, watch any number of presentations but in the end you still need to type the code. You may be disappointed to hear that Java is not a GUI language. Sure we can use Java to make some neat Web pages but essentially it is a character based language. Java is unusual in that we use a compiler to compile our code and then use a interpreter to run it, we will explain in greater detail later why this is so. No first lesson in a new language could be complete without writing a "Hello World" program, something simple to wet our appetites with. You may like to create a new directory if you haven�t done, to keep all your code handy in the one spot. What we need to create our code is a text editor. The Windows notepad editor is just fine, you may use your favorite word processor as long as you remember to save you files as text. WARNING - Do not use the DOS editor as it only allows you to save files as 8.3 format. The Java source code must be saved with the .java extension. Lets start. Copy 'n paste or type this program into your editor. /* Lesson 1 */ /** This is our Hello World application */ class Helloworld { public static void main (String[] arguments) { System.out.println("Hello World."); // More comments } } Hint - When learning something new I always find it better if I do the typing. Feel free to replace "Hello World" with any other text you like. Now what does all that mean ?. The �Class� statement transferred to English means, �this programs name is HelloWorld�. The �main� statement is the start of our Java application. The curly brackets are used to group logical pieces of code together. Hint - indent the layers of the brackets, it makes your code more readable and maintainable by other programmers. The Java code on the previous page is logically equivalent to the following code, which one would you like to maintain. /* Lesson 1 */ /** This is our Hello World application */ class Helloworld { public static void main (String[] arguments) { System.out.println("Hello world "); // More comments } } What are these things /* */, /** */ and //. All of the above are comments, anything between the /* */ characters are ignored by the Java compiler. The /** */ characters are a documentation comment, the Java compiler ignores these also. The javadoc tool uses these comments when preparing automatically generated documentation. // Anything after these characters on a line are also ignored by the Java compiler. So now lets save the program as a text file with the extension .java, the file name must be the same as the class name including the capitalization. That is HELLO is not equal to Hello or hellO. All java programs must be compiled before we can run them, so go to the directory where the java code resides and type the line javac Helloworld.java from the DOS prompt if you are using Win 9x or the command prompt if you are using Win NT. If the program compiles without any errors (the java compiler only complains if there are errors) a new file is created called Helloworld.class. If you have any errors check Your spelling Your capitalization Your brackets any semicolons. Once your program has compiled without any errors then we are going to run it. Type the line java Helloworld from the DOS prompt if you are using Win 9x or the command prompt if you are using Win Nt. You should see the output �Hello World�. Congratulations you have completed your first Java program. In our next lesson we will extend our Helloworld program and convert it to an applet that we can run from the Web. Go To The Forums Take Our Survey Java Lessons Javascript Lessons SQL*PLus Lessons PL/SQL Lessons Oracle DBA Lessons Java Tips Javascript Tips Oracle Tips Get all the latest tips, tricks and lessons direct to your in-tray. Your E-Mail Address: Lesson Two - Our First Web Applet Following on from our first lesson where we created our �Hello World� application we will see what else we can do with a simple java application, then we will convert our �Hello World� application to an applet and deploy it on a Web Page. Lets start. Cut 'n paste or type this program into your editor. /* Lesson 2 */ /** This is our weight application */ class weight { public static void main(String[] arguments) { int lbs = 90; System.out.println("Ally McBeals weight is now " + lbs + " lbs."); } } Now what is new in this program? We have declared a variable called lbs and it is an integer (a number to the laymen) and our output consists of concatenated strings and the lbs variable. Now lets compile the application by typing javac weight.java from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. When you have no compilation errors with your code then run it by tying the command: java weight also from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. You should see the output: �Ally McBeals weight is 90 lbs.�. You may disagree with what I think she may weigh so what we are now going to do is pass some arguments to the application with what you think she may weigh. Cut 'n paste or type this program into your editor. /* Lesson 2 */ /** This is our weight2 application */ class weight2 { public static void main(String[] arguments) { int lbs = 0; if (arguments.length > 0) lbs = Integer.parseInt (arguments[0]); System.out.println("Ally McBeals weight " + "is now " + lbs + " lbs."); } } Lesson Two - Our First Web Applet (Cont.) Now what is new in this program? We check if we have passed any arguments to the application by using the line �if (arguments.length > 0)� and when then use �lbs = Integer.parseInt (arguments[0])� to set the value of the variable lbs to the parameter that we used on the command line. Now compile the application by typing the command: javac weight2.java. When you have no compilation errors then run it by typing java weight2 77. You should see the output �Ally McBeals weight is 77 lbs.�. Try it for yourself. Now lets convert our weight application to a java applet. /* Java 101 - Lesson 2 */ /** This is our weightapplet applet */ public class weightapplet extends java.applet.Applet { int lbs; public void init() { lbs = 90; } public void paint(java.awt.Graphics g) { g.drawString("Ally McBeals weight is " + lbs + " lbs.",5,50); } } Compile the applet using javac weightapplet.java. Applets cannot be tested using the java interpreter tool. You have to put them on a web page and view them in one of two ways. Use a web browsers such as the current versions of Netscape Navigator or MS Internet Explorer Use the appletviewer tool that comes with the Java Developers Kit. Save the file as weightapplet.htm Type the following line appletviewer weightapplet.htm and our weight estimate will appear in the viewer. We will discuss applets in more detail later in our course. Lesson Three - Variables and Strings Today we will cover what a variable is, how to declare it, Operators and using string variables. Our lesson will cover five types of variables, not that this is all but with these five you will still be able to do almost everything with Java, secondly we don�t want to overloaded you with variable types you don�t need at this stage. /* Lesson 3 */ class lesson3a { public static void main (String[] arguments) { // More Variables to follow int lotsadigits; float pi; } } The piece of code above has declared two different types of variables. int lotsadigits; has defined a variable called lotsadigits that is an integer (ie a whole number) that can contain a number in the range -2.14 billion to 2.14 billion. float pi; has declared a variable pi (remember back to High School when you had to calculate the area of a circle) that is the type float . These are not whole numbers e.g. 3.1428571428571428571428571428571. Lesson Three - Variables and Strings (Cont.) If Java could only store numbers it would never have got out of the development lab! /* Lesson 3 */ class lesson3b { public static void main (String[] arguments) { // More Variables to follow int lotsadigits; float pi; char initial = 'E'; String surname = "Mcpherson"; } } Note: When using char type variables you must use single quotes and when using Strings you must use double quotes. Please cut 'n paste or type this program into your editor. /* Lesson 3 */ /** This is our weight application again*/ class lesson3c { public static void main(String[] arguments) { float lbs = 90; lbs = lbs + 10; lbs = lbs - 20; lbs = lbs / 2; lbs = lbs * 3; System.out.println("Ally McBeals " + "weight is now " + lbs + " lbs."); } } Lesson Three - Variables and Strings (Cont.) Now compile the application by typing the command javac lesson3c.java. from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. When you have no compilation errors then run it by typing the command java lesson3c You should see the output �Ally McBeals weight is 120 lbs.�. The last variable type that we will discuss for the moment is the boolean type, a boolean variable has one of two states, �TRUE� and �FALSE�. Some examples of boolean variable are, �Is the account Overdrawn�, �Has the user pressed a key�, these are just two examples of boolean variables, we will use boolean variables later in our class. How to display special characters in Strings. When a string is created or displayed it is enclosed in double quotes, what do we do if we want to display the quotes, then we need to protect them with a \ character. Please cut 'n paste or type this program into your editor. /* Lesson 3 */ class lesson3d { public static void main(String[] arguments) { System.out.println("Calista Flockart is " + "the star of " + "\"Ally McBeal\"."); } } Lesson Three - Variables and Strings (Cont.) Now compile the application by typing the command javac lesson3d.java. from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. When you have no compilation errors then run it by typing the command java lesson3d You should see the output �Calista Flockart is the star of "Ally McBeal".� Incrementing and Decrementing a Variable. Because this is done so often there is a simplified way of doing it in Java. To increment the variable x by one just use the following statement: x++; Conversely to decrement the variable x by one use the following statement: x--; Other special characters. \� Single quotation mark. \" Double quotation mark. \\ Backslash. \t Tab. \b Backspace. \r Carriage Return. \f Formfeed. \n Newline. Lesson Three - Variables and Strings (Cont.) Comparing strings: To compare strings in Java we use the equals() method. Please cut 'n paste or type this program into your editor. /* Lesson 3 */ class lesson3e { public static void main(String[] arguments) { String firstName = "Ally"; String firstGuess = "Fred"; String secondGuess = "Ally"; System.out.println("Ms McBeals firstname is " + firstGuess + "?"); System.out.println("Answer: " + firstName.equals(firstGuess)); System.out.println("Ms McBeals firstname " + "is " + secondGuess + "?"); System.out.println("Answer: " + firstName.equals(secondGuess)); } } Compile the application by typing the command javac lesson3e.java from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. When you have no compilation errors then run it by typing the command java lesson3e You should see the output �Ms McBeals firstname is Fred?� Answer: False �Ms McBeals firstname is Ally?� Answer: True Lesson Three - Variables and Strings (Cont.) "How Long is a String ?" To determine the length of a string in Java we use the length() method for the string. Please cut 'n paste or type this program into your editor. /* Lesson 3 */ class lesson3f { public static void main(String[] arguments) { String firstName = "Ally"; System.out.println("The length of " + "\"Ally McBeals\" " + " firstname is " + firstName.length()); } } Compile the application by typing the command javac lesson3f.java from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. When you have no compilation errors then run it by typing the command java lesson3f You should see the output �The length of "Ally McBeals fistname is 4�. Lesson Three - Variables and Strings (Cont.) Changing a strings case. To convert a string to upper or lower case we use the methods toLowerCase() or toUpperCase() respectively. Please cut 'n paste or type this program into your editor. /* Lesson 3 */ class lesson3g { public static void main(String[] arguments) { String firstName = "Ally"; System.out.println("Lets convert " + firstName + " to lower case " + firstName.toLowerCase()); System.out.println("Lets convert " + firstName + " to upper case " + firstName.toUpperCase()); } } Now compile the application by typing the command javac lesson3g.java from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. When you have no compilation errors then run it by typing the command java lesson3g You should see the output �Lets convert Ally to lower case ally.' 'Lets convert Ally to upper case ALLY'. Lesson Four - Conditional Tests Today's lesson will describe what conditional tests are ,how we use them and how to use programming loops. A conditional test is asking the computer a question. i.e. if I have $20 in my account I can buy the CD. If Statements. If you want to test a condition in Java the easiest way is to use an if statement. Please cut 'n paste or type this program into your editor. /* Lesson 4 */ class lesson4a { public static void main (String[] arguments) { int balance = -1; if (balance < 0) System.out.println("Your Account " + "is overdrawn "); } } Now compile the application by typing the command javac lesson4a.java. from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. When you have no compilation errors then run it by typing the command java lesson4a You should see the output �Your Account is overdrawn�. Lesson Four - Conditional Tests (Cont.) If - Else Statements. If you want the program to do one thing if the answer to a question is true but something else if the answer if false then you will need to use an if - else statement. Please cut 'n paste or type this program into your editor. /* Lesson 4 */ class lesson4b { public static void main (String[] arguments) { int balance = 3; if (balance < 0) System.out.println("Your Account is " + "overdrawn "); else System.out.println("Your available funds " + "are $" + balance + "."); } } Compile the application by typing the command javac lesson4b.java from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. When you have no compilation errors then run it typing the command java lesson 4b You should see the output 'Your available funds are $3.' It is possible to 'chain' if - else statements where there are more than two possible outcomes for a question. Please cut n' paste or type this program into your editor. /* Lesson 4 */ class lesson4c { public static void main (String[] arguments) { int balance = 0; if (balance < 0) System.out.println("Your Account is " + "overdrawn "); else if (balance == 0) System.out.println("There are no funds " + "in you account"); else System.out.println("Your available funds " + "are $" + balance + "."); } } Compile the application by typing javac lesson4c.java from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. When you have no compilation errors then run it by typing java lesson 4c You should see the output 'There are no funds in you account'. Lesson Four - Conditional Tests (Cont.) Switch Statements. A way to test for a variety of different conditions is to use the switch statement. Please cut n' paste or type the file into your editor. /* Lesson 4 */ class lesson4d { public static void main (String[] arguments) { int month = 0; if (arguments.length > 0) month = Integer.parseInt (arguments[0]); switch (month) { case (1): System.out.println("January"); break; case (2): System.out.println("February"); break; case (3): System.out.println("March"); break; case (4): System.out.println("April"); break; case (5): System.out.println("May"); break; case (6): System.out.println("June"); break; case (7): System.out.println("July"); break; case (8): System.out.println("August"); break; case (9): System.out.println("September"); break; case (10): System.out.println("October"); break; case (11): System.out.println("November"); break; case (12): System.out.println("December"); break; default: System.out.println("Month Does not exist"); } } } Please compile the application by typing the command javac lesson4d.java from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. When you have no compilation errors then run it by typing the command java lesson 4d (and a number for the month of the year). You will see the month displayed for the corresponding number that you entered. If you did not enter a number between 1 - 12 then you will see the message "Month Does not exist". The default clause is a catch all if none of the other statements were true. The default clause is not compulsory. Lesson Four - Conditional Tests (Cont.) Comparison Operators. The < in the programs mean the same as it would be used in a math class, as a less than symbol. There are six comparison operators that we can use in a Java program, they are < Less than. <= Less than or equal to. > Greater than. >= Greater than or equal to. == Equal to. != Not equal to. Now let's start to go around in circles - Loops. There are three types of loops in Java they are the for loop, while loop and the do while loop. A For loop is asking the computer to perform a particular task a set number of times Please cut n' paste or type this program into your editor. /* Lesson 4 */ class lesson4e { public static void main (String[] arguments) { for (int number = 0; number < 100; number++) { System.out.println("Number " + number + "."); } } } Now compile the application by typing the command javac lesson4e.java from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. Lesson Four - Conditional Tests (Cont.) When you have no compilation errors then run it by typing the command java lesson 4e The program will write the numbers 0 - 99 on the terminal.. We can now perform the same task using the while loop. Please cut n' paste or type this program into your editor. /* Lesson 4 */ class lesson4f { public static void main (String[] arguments) { int number = 0; while (number < 100) { System.out.println("Number " + number + "."); number++; } } } Now compile the application by typing the command javac lesson4f.java from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. When you have no compilation errors then run it by typing the command java lesson4f The program will write the numbers 0 - 99 on the terminal.. Lesson Four - Conditional Tests (Cont.) We can now perform the same task using the DO-WHILE loop. Please cut n' paste or type this program into your editor. /* Lesson 4 */ class lesson4g { public static void main (String[] arguments) { int number = 0; do { System.out.println("Number " + number + "."); number++; } while (number < 100); } } Now compile the application by typing the command javac lesson4g.java from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. When you have no compilation errors then run it by typing the command java lesson 4g The program will write the numbers 0 - 99 on the terminal Lesson Four - Conditional Tests (Cont.) Exiting a loop. The normal way to exit a loop is for the tested condition to become false but there may be occasions you what to exit earlier and to do so we use the break statement. Please cut n' paste or type this program into your editor. /* Lesson 4 */ class lesson4h { public static void main (String[] arguments) { int number = 0; do { number++; System.out.println("Number " + number + "."); if (number == 50) break; } while (number < 100); } } Now compile the application by typing the command javac lesson4h.java from the DOS prompt if you are using Win 9x or the Command Prompt from Win NT. When you have no compilation errors then run it by typing the command java lesson4h The program will write the numbers 1 - 50 on the terminal. We have seen that it is possible to write three different looping constructs to perform the same thing but in three different ways. We use the for loop if we wish to execute a piece of code a set number of times, the while loop if we want to test a condition before we execute the code in the loop and the do - while loop if we wish to execute the code in the loop at least once before we test the loop condition. Lesson Five - Using Arrays In today's lesson we will discover how to store information with arrays. The basic way to store information in a computer is to use a variable, these are only as good as the number of variables we declare. Say suppose we want to keep a list of items that are all of the same type. i.e. all movie titles. We could declare 101 variable names to store the movie titles of we could declare an array to store the 101 movie titles. We will cover Creating an array What a dimension of an array is. Giving a value to an array element. Extracting a value from an array element. Changing the information in an array. Making multidimensional arrays. Creating Arrays. You can create arrays for any type of information that can be stored as a variable. All the following statements create an array of variables. string[] babyName; int[] babyAge[]; boolean babyWeight; The above statements created three arrays but there was nothing stored in them, to do so you must use the new statement and specify how many elements are in the array. The following statement creates an array called babyName and sets aside an area to store 40 entries. string[] babyName = new string[40]; Lesson Five - Using Arrays (Cont.) It is possible to assign values to an array when it is declared like a variable, the following statement creates an array called babyAge and assigns ages to the array. int[] babyAge = {1,4,3,5}; The values to be placed in the array are between the { and the } characters and separated by commas. Each element of the array must be of the same type, the number of elements in the array is not specified because the it is set to the number of elements set. Using Arrays. Arrays can used in a programs as you would any other variable, once you refer to the element number you can use the array element anywhere that a variable could be used. Array elements are reference from 0 to n-1 where n is the number of elements that have been set in the array. The array babyName that was declared earlier could be used to reference elements 0 through 39. If you attempted to reference element babyName[40] then you would encounter an 'array out of bound' error. To avoid referencing an element that is out of bounds it is possible to check of the number of elements in the array by using the following statement. Please cut n' paste or type this program into your editor. /* Lesson 5 */ class lesson5a { public static void main (String[] arguments) { int[] babyAge = {1,4,3,5}; System.out.println("There are " + babyAge.length + " babies."); } } Lesson Five - Using Arrays (Cont.) Now compile the application by entering the command javac lesson5a.java. at the DOS prompt if you are using Win 9x or the command prompt if you are using Win NT. When you have no compilation errors then run it by typing the command java lesson5a. You should see the output �There are 4 babies.� The highest element number that is addressable in the array babyAge is [3]. Multidimensional Arrays Arrays can have more that one dimension, in fact as many dimensions that you need but keep in mind they can use a lot of memory. To create an array that uses two dimensions we use the following statement. String[] babyDetail = new String[5][5]; Lesson Five - Using Arrays (Cont.) Here is an example of using one dimensional arrays. Please cut n' paste or type this program into your editor. /* Lesson 5 */ class lesson5b { public static void main (String[] arguments) { String[] sitcoms = {"Friends", "Just Shoot Me", "Darma and Greg", "Zoe"}; // Please Don't shoot me // for my taste in television !!! for (int count = 0; count < sitcoms.length; count++) { System.out.println("Show Name " + sitcoms[count]); } } } Now compile the application by entering the command javac lesson5b.java at the DOS prompt if you are using Win 9x or the command prompt if you are using Win NT. When you have no compilation errors then run it by typing the command java lesson5b Lesson Six - Creating Objects In today's lesson we will create our first object. Object Oriented Programming is a complicated term for an elegant way of describing what a computer program is and how it works. We will cover Understanding objects How attributes describe an object What determines how objects behave Combining objects Inheriting from other objects Creating an object How Object Oriented Programming Works. Each Java program that you have written or will write can be thought of as an object, like anything else in the real world, such as a car, bike, fridge or people. People consist of a head ( I have known some with more that one but I won't go into that), two arms, two legs, two hands a torso etc. Each part of the body performs specific tasks and has things that make it different from the rest of the body. If you break down computer programs the same way as you have done with a persons body then you are performing Object Oriented Programming or OOP. An object contains two things, attributes and behavior. Attributes describe the object and the behavior describes what the object does. With Java we create an object by using a class as a template. The class is a master copy of the object that is consulted to determine which attributes and behavior an object should have. Every Java program that you create will be a class because each one has used a template for the creation of new objects. Lesson Six - Creating Objects (Cont.) Objects in Action. Consider the PC that you are using at the moment, describe the PC in detail, its' case, power supply, hard disk(s), motherboard, modem, Graphics Card, Monitor. They are all objects that combine to make your PC. Each object exist independently of the other. The modem object does its' job without requiring any help from the monitor object. What Objects Are. Objects are created by using a class of objects as a guideline or template. The following is a class. public class dog { } Any object created from this class can't do anything because it doesn't have any attributes or behavior. public class dog { String name; public void speak() { System.out.println("Woof Woof"); } } The dog class now looks like the programs we have already written except that it has a public statement alongside it. The public statement means that the class is available for use by the public - in other words, by any programs that want to use the dog object. The first part of the dog class creates a string variable called name. This variable is an attribute of the object, this is what distinguishes one dog from another. The second part of the dog class is a method or behavior called speak(). This method has one statement, the System.out.println statement to display 'Woof Woof'. Lesson Six - Creating Objects (Cont.) If you wanted to use a dog object in your program then you could you the following statement dog myDog = new dog(); We can now set the name of myDog myDog.name = "Barney". /* He was named after Barney Rubble, not a purple dinosaur */ To make Barney speak by calling the speak method we could use the following: myDog.speak(); The computer will respond with "Woof Woof" unlike the real Barney. Understanding Inheritance. The final selling point of Object Oriented Programming is inheritance. When you start creating objects for use in programs, you will find that some objects you want are a lot like other objects that have already been developed. Building an Inheritance Hierarchy A class that inherits from another is called a subclass, and the class that is inherited from is called a superclass. Creating an Object public class mammal { String name; public void sleep() { System.out.println("zzzzzzzzzzzzzzzzzzz"); } } Cut n' paste or type this program into your editor. Compile the code using javac mammal.java. Lesson Six - Creating Objects We now have a public class called mammal that has the attribute name and the method sleep() i.e. it snores. public class dog extends mammal { public void speak() { System.out.println("Woof Woof"); } } Cut n' paste or type this program into your editor. Compile the code using javac dog.java. We now have a subclass dog of the superclass mammal, dog has a attribute name that it has inherited from the superclass mammal and the methods sleep() and speak(). /* Java Lesson 6a */ class lesson6a { public static void main(String arguments[]) { dog doggie = new dog(); doggie.name = "Barney"; System.out.println("Barney is Barking"); doggie.speak(); System.out.println("Barney is sleeping"); doggie.sleep(); } } Cut n' paste or type this program into your editor. Compile the code using javac lesson6a.java. When there are no errors, run the program using java lesson6a. You should see the following output. 'Barney is Barking' 'Woof Woof' 'Barney is sleeping' 'zzzzzzzzzzzzzzzzzzz' Are we now all clear with Object Oriented Programming OOP and inheritance. I hope so !!. Lesson Seven - Describing Objects In today's lesson we will learn how to describe our objects. Objects require two things to perform their required tasks, attributes and behavior. Attributes are the information stored within the object. They can be variables or they can be other objects such as the dog class in our example in lesson6a. Behavior is the group of statements used to perform actions within the object. Each of these groups is called a method. Creating Class Variables. The attributes of an object represent the variables that are needed for the object to function. An objects variables can be used throughout its program in any of the methods the object includes. You can create variables immediately after the class statement that creates the class and before any methods. The following code begins a class called dog with an integer variable called totDogs. public class dog { public integer totDogs; } Only one copy of this variable exist for the whole class, all the variable we have created till now have been object variables. Class variables refer to a class of objects as a whole. We assign and refer to class variable as we would object variables. Creating Behavior with Methods. Behavior describes all the different sections of a class that accomplish specific tasks. Each of these sections is called a method. All our programs to date have been using methods, for example println is a method to display text on a screen. Lesson Seven - Describing Objects (Cont.) Declaring a Method. Creating a method is similar to creating a class, the difference is that methods can return a value after they are handled, if the method is not to return a value then we use a void statement. boolean public healthyDog (String name) { boolean hasFleas = false; // Statements to check if the dog has fleas return true; } The healthyDog method is used to check if the dog has fleas. The method takes a single argument, the string variable called name, this is the name of the dog that will be checked for fleas. When a method returns a value, you can use the method as part of an assignment statement. e.g.. if (doggy.hasFleas(dogName)) System.out.println("The dog " + dogName + " has fleas "); Similar Methods with Different Arguments Two methods can have the same name if they have a different number of arguments or the arguments are of different types. i.e. void doggyName() { System.out.println("My dogs name is Barney"); } void doggyName(String Name) { System.out.println(doggyName); } Lesson Seven - Describing Objects (Cont.) Constructor Methods When you create an object in a program, we us the statement dog doggy = new dog(); This statement creates a new dog object called doggy based on the class dog. We can assign the doggy variable when we create it by doing the following. dog doggy = new dog("Barney"); Class Methods. Like class variables, class methods are a way to provide functionality associated with an entire class instead of a specific object. Variable Scope Within Methods. When you create a variable or an object inside a method in one of you classes, it is useable only inside that method. You can only use a variable in more that one method if it was created as an object or class variable after the class statement of the beginning of the program. Using the this Keyword. Because we can refer to variable and methods in other classes along with variables and methods in our own class, we can make things clearer with the this statement. The this statement is a way to refer in a program to its own object. A variable called dogName exists within the scope of the checkFleas() method, but isn't the same variable as the object variable dogName. To refer to the current objects variable called dogName we could use the this statement as follows. System.out.println("Dog Name " + this.dogName); Lesson Eight - Inheritance In today's lesson we will learn all about inheritance. When you create a program as an object, with a set of attributes and behavior, you have created something that is ready to pass these qualities on to it's children or subclass. This is called inheritance, every superclass (parent) gives its qualities to its subclass (child). Without knowing it you have used inheritance in almost every java program that you have written in this course. Every time that you have used one of the standard Java classes such as String, Math and System you have used inheritance. The program that you have written has used the String class has inherited the behavior to be able to use characters. The Family Tree. With all family trees we inherit the characteristics of our parents, grand parents and great grand parents. We can inherit that funny nose from you mothers side of the family, the buck teeth from you father, the red hair from you great grandfather etc. But we don't inherit anything from our Aunts and Uncles or cousins, the same holds true for Java classes. Inheriting Behavior and Attributes. The behavior and attributes of a class are the combination of two things, its own behavior and attributes and the behavior and attributes of all its superclasses. See can can really blame your parents for all your bad points!. Overriding Methods. Where there has been behavior defined in a superclass, it can the overridden in a subclass by redefining the behavior. Just because your father was a tax cheat and embezzler it is possible to overwrite the behavior in the child (subclass). Creating a new method in a child to change the behavior inherited from a parent is called overriding the method. Lesson Eight - Inheritance (Cont.) Lets return to the example of inheriting canine behavior from lesson 6. Please cut n' paste or type this program into your editor. public class mammal { String name; public void sleep() { System.out.println("zzzzzzzzzzzzzzzzzzz"); } } Now compile the code by typing the command javac mammal.java from the DOS prompt if you are using Win 9x or the command prompt if using Win NT. We now have a public class called mammal that has the attribute name and the method sleep(). Please cut n' paste or type this program into your editor. public class dog2 extends mammal { public void speak() { System.out.println("Woof Woof"); } public void sleep() { System.out.println("Snore Snore Snore"); } } Now compile the code by typing the command javac dog2.java from the DOS prompt if you are using Win 9x or the command prompt if using Win NT. We now have a subclass dog2 of the superclass mammal, dog2 has the attribute name that it inherited from the superclass mammal and the methods sleep() and speak(). Lesson Eight - Inheritance Please cut n' paste or type this program into your editor. /* Java Lesson 8a */ class lesson8a { public static void main(String arguments[]) { dog2 doggie = new dog2(); doggie.name = "Barney"; System.out.println("Barney is Barking"); doggie.speak(); System.out.println("Barney is sleeping"); doggie.sleep(); } } Now compile the code by typing the command javac lesson8a.java from the DOS prompt is you are using Win 9x or the command prompt if you are using Win NT. When there are no errors, run the program by typing java lesson8a. You should see the following output. 'Barney is Barking' 'Woof Woof' 'Barney is sleeping' 'Snore Snore Snore' See we have overridden the mammals behavior to sleep quietly with the Barneys habit of snoring. I trust you all now understand the concept of inheritance of attributes and behavior with Java classes. Lesson Nine - Applets In today's lesson we will learn how applets work. This is where all the interest with Java is. When a Java applet is encountered on a Web page it is downloaded by the browser. Because applets must be downloaded off a web page each time they are run, they are smaller than most applications to reduce the download time. As the applets are run on the computer of the person using the applet, there are numerous security restrictions in place to prevent malicious code from being run. Standard Applet Methods. All applets are subclasses of the Applet subclass, that is part of the java.applet package of classes. Being part of this hierarchy enables the applets that you write to use all the behavior and attributes they need to be able to run from a Web page. In applications, programs begin running with the statement of the main() block statement and end with the last } that closes the block. There is no main method in a Java applet, so there is no set starting place for the program. Instead, an applet has a group of standard methods that are handled in response to specific events as the applet runs. Unlike applications, applet classes must be public in order to work public class lesson8a extends java.applet.Applet { } This class inherits all the methods that are handled automatically when needed. init(), paint(), start(), stop(), and destroy(). If you want anything to happen in an applet you must override these methods. The two methods that you will override the most often are paint() and init(). Lesson Nine - Applets (Cont.) The paint() Method. The paint() method is part of every Java applet that you will write. Without it you cannot display anything. When you display or redisplay anything in a java applet you will use the paint() method. The paint method uses an argument. public class paint(Graphics screen) { } If you are going to use the Graphics object in you applet you must first add the following import statement before the class statement at the beginning of the source code. import java.awt.Graphics The init() Method. The init() method is handled only once when the applet is run. Hence it is generally used to set up variables that are needed in the applet i.e. fonts, colors etc. A word or warning, any objects or variable created in the init() method only exist within the scope of that method. The start() Method. When the applet starts running the start() method will be handled. The the applet begins when the init() method is handled then the start() method. For the start method to be handled a second time the execution of the applet must be stopped. The stop() Method. The stop method is handled when execution of the applet stops. This can occur when the user leaves the Web page or when the stop method is called directly from the Java applet. The destroy() Method. The destroy method is handled immediately prior to the applet closing down. Lesson Nine - Applets (Cont.) The destroy() Method. The destroy method is handled immediately prior to the applet closing down. Placing an Applet on a Web Page Applets are placed on Web pages in the same way any other objects are placed on a Web page, using HTML. We use HTML tags to surround our Java applet. This requires a Java enabled Browser The CODE identifies the name of the applet to run. The CODEBASE identifies the directory to find the applet code if the current directory is not used. The HEIGHT and WIDTH identify the size that is reserved on the browser to display the applet. In between the and the it is possible to display something that non Java enabled browsers can see. In the above example we display a short message. Lets create an applet. Please cut n' paste or type this program into your editor. import java.awt.Graphics; public class lesson9c extends java.applet.Applet { int netValue; public void init() { netValue = 0; } public void paint(Graphics screen) { screen.drawString("My Net value is $" + netValue, 5, 50); } } Now compile the applet by typing the command javac lesson9c.java from the DOS prompt if you are using Win 9x or the command prompt if you are using Win NT.
Hosted by www.Geocities.ws

1