Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Java 211 – Lecture IV
Intro to Objects & Applets
Yosef Mendelsohn
A Brief Introduction to Classes & Objects
Objects are much more powerful than the primitive data types… Today we will not be
discussing how to create classes of our own, but rather how to use a few of the classes
that come pre-packaged with Java. The ones we will focus on are the String class and the
Math class.
Classes typically (pretty much without exception) contain a collection of methods.
Sometimes these methods are intended to be used only with objects of the class (which, I
realize, means little to you at this point). Other methods are intended to be used on their
own. For example, a method that accepts one argument of type double and returns its
square root is ‘stand alone’. Another ‘stand alone method’ would be one that accepts two
integers and returns the average.
Take a look at the API (application programming interface) of the class called ‘Math’.
Ignore the top stuff and instead scroll down a little ways until you see the section called
‘Method Summary’. Here you see a collection of methods that are available for you to
use. For example, supposing you wanted to use the method called ‘sqrt’. Note the
signature:
static double sqrt (double a)
This tells you that the method accepts one argument of type double. By reading the
information in the API you can also see that the method returns a double corresponding
to the square root of ‘a’.
Therefore, you should be able to invoke the method by typing something like:
double x = sqrt(9.0);
//x will be set to 3.0
Right? Actually, WRONG!
The problem is one of context. Consider where you would see this line of code:
public class Test
{
public static void main (String[] args)
{
double x = sqrt(3.0); //will give a ‘No such method’ error
System.out.println(x);
}
}
Using our favorite algorithm we say: “The system looks for a method called ‘sqrt’ that
accepts ‘1’ argument(s) of type ‘double’.” Will it find such a method?
No… Why? Because the method lives in a completely different class.
In other words, we somehow need to indicate to the system to look for the ‘sqrt’ method
in the Math class. How do we do this? By typing: Math.sqrt(…) //note the dot!
By changing the line to read:
double x = Math.sqrt(9.0);
we tell the system where to go to look for the sqrt method.
Note: This method of invoking methods (ie: preceding the method name by the class
name) will NOT work for all methods. It will only work for methods that have the word
‘static’ in their signature. For now, then, you should put the word static before all of your
methods because they are meant to be stand alone. (You will understand more about
‘stand alone’ methods when we discuss classes in more detail).
The String Class
Let’s take a look at the String class: As before, scroll down to the Method Summary
section. The same ideas apply. Any method that is preceeded by the word ‘static’ may
be invoked simply by giving the name of the class. However, note that the word static
does not show up in the signature of any of these methods?
What does this mean? It means that you may not invoke the method simply by giving the
name of the class. So what’s going on?
The answer lies in the fact that these methods are not meant to be ‘stand alone’ methods.
For example, look at the method ‘length()’. Note that this method returns the length of a
string. In other words, the length() method only makes sense if there is a String variable
around.
System.out.println( length() ); //makes no sense--length of what??
//Also, the system won’t be able to find this method.
System.out.println( String.length() ); //still makes no sense
//You’re telling the system where to find the method but nothing else
//You’ll also get an error telling you that ‘length()’ is not
//a static method
String s = “Hello DePaul!”;
System.out.println( s.length() ); //much better!! (outputs ‘12’)
In the last example you see that the length method now ‘makes sense’ since it has a
String variable attached to tell you the length of.
Note: The variable ‘s’ also serves the purpose of telling the system where to look for the
method ‘length()’. Because ‘s’ is a variable of type String, the system looks in the String
class for the method.
More examples:
String s = “Hello DePaul!”;
System.out.println( s.charAt(0) ); //outputs an ‘H’
System.out.println( s.charAt(12) ); //outputs a ‘!’
System.out.println( s.charAt(13) ); //error – there is no 13th index!
System.out.println( s. charAt (s.length()-1) ); //okay too!
Comparing Two Strings
We need to address one pecuiliar thing in Java. Again, the reasons will make sense when
we talk about a subject called ‘References’ later in the course. Supposing you have two
strings:
String s1 = “Hello DePaul!”;
String s2 = “Hello DePaul!”;
The boolean expression: (s1 == s2) will return FALSE! Again the reasons will be
explained later… For now, be aware that to compare two strings you would have to do
something along the lines of:
if ( s1.equals(s2) ) //returns true
if ( s1.equals(“Hello DePaul!”)) //also returns true
Strings are “immutable”:
This means that you can’t modify an existing string on the fly. For example:
String s1 = “hello DePaul”;
System.out.println( s1.toUpperCase() ); //outputs ‘HELLO DEPAUL’
System.out.println( s1 ); //will output ‘hello DePaul’ (ie same case)
The point is that even though we invoked s1.toUpperCase(), we still have not made
any changes to the variable ‘s1’.
To make a change to s1, then, we would need to reassign the variable as in:
s1 = s1.toUpperCase();
System.out.println( s1 ); //will output HELLO DEPAUL
The ‘static’ qualifier:
Just to review the idea of static methods one more time, recall that if a method has the
word static in its header, you can invoke the method by preceding the method call
with name of the class and a dot. Some examples:
System.out.println( Math.sqrt(25.0) ); //outputs 5.0
System.out.println( Math.max(-3.4, 4.9) ); //outputs 4.9
MethodsPractice.countToTen(); //counts from 1 to 10
ArrayExamples.outputArray( doubleArray );
As was discussed in the past, in order for the previous two lines to work, you should keep
the MethodsPractice and ArrayExamples classes in the same directory as your other files.
As you progress in your Java experience you will learn howto group these classes in
packages and place them in different locations on your hard drive.
Applets
-
-
A Java application is a stand-alone Java program that can be run on any machine
that has a Java interpreter (JVM).
An applet is a Java program that is intended to be embedded into an HTML
document, and executed by a web browser. This works because Java-capable
browsers have built-in Java interpreters.
Not all broswers can execute Java applets. Some that can include: Netscape,
Internet Explorer, HotJava,
The SDK (and Textpad) both have “Applet Viewers”. These are little programs
that allow you to view your applets without having to use your web browser.
Java applets were the first kind of true executable programs that could be run
using WWW software.
Unlike Java applications, Java applets are considered to be part of a “larger”
program (context) and as such, do not have a main() method.
Packages:
- In order to create an applet, we will need to “extend” (this term will be explained
later) the Applet class. In a sense, we are taking a pre-existing class, and
tweaking it for our purposes. However, to make use of this class, we must import
it. The proper statement is:
import java.applet.Applet;
import java.awt.*;
- The second statement is where we import a number of different classes that we
use for creating graphics. (AWT stands for abstract windows toolkit).
paint() method
- Every time an applet is loaded, a method called ‘paint()’ is invoked automatically.
This is because all applets have a graphical base. In order to view the applet, it
must be ‘painted’ on the screen.
- The paint() method takes one argument of type ‘Graphics’. Objects of type
Graphics enable us to draw various shapes such as rectangles, ovals, lines,
Strings, etc.
- This same object (of type Graphics) is said to represent a “context” with
which we interact. Applets can have multiple Graphics contexts, although we
will focus on just one context per applet for the time being.
- Each graphics object has its own coordinate system. The (0,0) coordinate is
the upper left hand corner of the context.
- Einstein.java
Executing the applet on the web – An HTML Primer
Web browsers display their information using a fairly simple language called HTML.
HTML is neither a programming language, nor a scripting language. It is called a
‘markup language’. HTML (Hypertext Markup Language) is composed of multiple tags
that tell the web browser how to display whatever follows. For example, to display text
in bold, the ‘programmer’ would enclose the appropriate text inside <B> and </B> tags.
(HTML is not case sensitive). Another example:
<I>When parsed by a browser, this text would be displayed
in italics.</I>
Images too can be displayed on a browser. The syntax is:
<img src=”my_family.jpg”>
The above tag indicates to the browser to look for an image file called ‘my_family.jpg’
and display it in the browser window.
Similarly, applets can be loaded into the browser window by a tag similar to the
following:
<applet code=”Einstein.class” width=350 height=175>
</applet>
This tells the browser to look for a bytecode file (note: not a source file!) called
‘Einstein.class’ and load it into the browser window. In other words, you must first
compile the source file into bytecode before you can run it as an applet. The browser
cannot compile the source code for you (nor would you want it to). Naturally, the class
file must be in the same directory as the HTML file (unless you provide a different path).
The height and width tags tell the browser the limits on the size of the applet.
With some specific exceptions, HTML files are given the extension .HTML or .HTM. So
to run the ‘Einstein’ applet, you would:
1. Take the <applet> tag listed above and save it inside a text file called
‘anything.htm’.
2. Place the Einstein.class file in the same directory as your HTML file
3. Inside your browser, type the path to your file. E.g. c:\temp\anything.htm
Graphics class
- Defined in the java.awt package
- Contains methods allowing us to draw several kinds of shapes
- These shapes can be outlines or filled
- For some shapes such as ovals, are bounded by a rectangle
- http://java.sun.com/j2se/1.3/docs/api/java/awt/Graphics.html
Color class
-
-
Also part of java.awt. package
Several instances of this are created for you. Each of these objects represents a
specific color. These objects include: Color.black, Color.cyan, Color.lightGray,
etc.
If you don’t want to use one of the predefined objects, you can use the RGB
colors for more accurate color representations.
-
-
Every Graphics context has a current foreground color. You can set this color
using the ‘setColor’ method of the Graphics class.
Every surface that can be drawn on has a current background color. You can
change this color by calling the ‘setBackground’ method of the component on
which you are drawing.
Snowman.java
Applet Methods
We’ve already discussed the ‘paint()’ method which gets called when you run the applet.
There are a few other methods that are also available to applet objects (recall that an
applet object is instantiated by the browser when the applet is run). Some of these
methods are automatically called at various points. Most of these method are built
around the idea that the applet is working within the context of a web page.
- init(): This method is invoked (automatically) when the applet is first loaded
into your browser. If you go to another web page and then return, the init()
method does not get invoked again. Same thing if you hit ‘refresh’. However, if
you shut down your browser and then restart it, loading your applet will also
cause the init() method to be invoked. It is used for various initializing actions.
- On Netscape, you can hit shift-Reload to re-invoke init(). On IE, you
can hit control-Reload.
- destroy(): Called when the browser (not the page) is exited.
- start(): Is invoked whenever the applet starts. If you leave the page and then
return, the start() method is invoked again. (This is because when you leave a
page, the applet becomes inactive).
- stop(): Invoked whenever you leave a page containing the applet (i.e.
whenever the applet becomes inactive).
- Proper regulation of the applet using start() and stop() is good
programming practice to avoid using up CPU process time when the
applet is inactive.
- The Applet API
- LineUp.java , StickFigure.java
- Question: Note the ‘setSize’ method at the end of the init() method in
LineUp.java. How can you look up that method to find out more about it?
- Answer: Your first guess should be that setSize() is a method of the Applet
class. However, a look at the Applet API shows no such method. It turns out
that the Applet class is “inherited” from another class. (More on this later).
For now, be aware of the fact that a class that has ‘inherited’ from a “parent”
class, can call any of the methods of the parent class. Applet objects inherit
from a few classes including Object, Component, and Container. The
setSize() method is a method of the Component class. Look towards the
bottom of the page on the Applet class page, and you can find this method.