introduction to java 113 th february 2004sifei he © 2004 introduction to java for cs381, ee4.web by...
TRANSCRIPT
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
1
Introduction to Java for Introduction to Java for CS381, EE4.WebCS381, EE4.Web
By Sifei [email protected] of ComputingSchool of EPSFebruary 2004
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
2
Abstract Class & methodAbstract Class & methodpublic abstract class MyFirstAbstractClass {
int anInstanceVariable;public abstract int aMethodMyNonAbstractSubclassesMustImplement();public void doSomething() {// a normal method}
}public class AConcreteSubClass extends MyFirstAbstractClass {
public int aMethodMyNonAbstractSubclassesMustImplement() {// we *must* implement this method}
}
• Some attempted uses of these classes:Object a = new MyFirstAbstractClass(); // illegal, is abstract
Object c = new AConcreteSubClass(); // OK, a concrete subclass
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
3
Programming flow controlProgramming flow control
• The while and do..while Statements • The for Statement • The if .. else if Statement • The switch … case Statement • The break statement (in loops and switch only)
• The continue statement (in loops only)
• The return statement (in method definitions only)
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
4
The “Circle” classThe “Circle” classpublic class Circle { // A class field public static final double PI= 3.14159; // A useful constant // A class method: just compute a value based on the arguments public static double radiansToDegrees(double rads) { return rads * 180 / PI; } // An instance field public double r; // The radius of the circle
// Two instance methods: they operate on the instance fields of an object public double area() { // Compute the area of the circle return PI * r * r; } public double circumference() { // Compute the circumference return 2 * PI * r; }}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
5
The “main” methodThe “main” methodpublic class Circle { public static final double PI= 3.14159; // A useful constant public double r; // The radius of the circle public Circle(double r) {this.r = r;} // Constructor public Circle() {} // Nothing Happen Here. public double area() { // Compute the area of the circle return PI * r * r; } public double circumference() { // Compute the circumference return 2 * PI * r; } //……… find them in the previous slides
}
public static void main(String[] args) { int input = Integer.parseInt(args[0]); Circle c = new Circle(); c.r = input; double result = c.circumference(); System.out.println(result); }
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
6
Put “main” in a new class?Put “main” in a new class?public class MakeCircle { public static void main(String[] args) {
int input = Integer.parseInt(args[0]);
Circle c = new Circle(); c.r = input; double circum = c.circumference(); System.out.println(circum); double a = c.area(); System.out.println(a); }}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
7
An AssociationAn Association
MakeCircle
main
Circle
radius
circumferencearea
creates instances of
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
8
The Circle exampleThe Circle exampleC:\>cd Java
C:\Java>javac Circle.java
C:\Java>javac MakeCircle.java
C:\Java>java MakeCircle 4
25.1327250.26544
C:\Java>java MakeCircle 5
31.415978.53975
C:\Java contains Circle.java and MakeCircle.java
C:\Java now also contains Circle.class and MakeCircle.class
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
9
The Members of a ClassThe Members of a Class
• Class fields– public static final double PI = 3.1416;
• Class methods– public static double radiansToDegrees(double rads) {…}
• Instance fields– public double radius;
• Instance methods– public double circumference() {…}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
10
Class FieldsClass Fields
public static final double PI = 3.14159
• A field of type double• Named PI (capitalise constants)• Assigned a value of 3.14159• The static modifier tags this as a Class Field
– Associated with the class in which it is defined
• The final modifier means it cannot be changed
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
11
Class Fields…Class Fields…
• There is only one copy of PI• Any instance of Class can refer to this
field as PI• PI is essentially a Global VariableBUT• Methods that are not part of Circle
access this as Circle.PI– No name collisions
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
12
Class MethodsClass Methods
public static double radiansToDegrees(double rads) {
return rads * 180 / PI; }
• Single parameter of type double and returns a value of type double
• Is essentially a “global method”// how many degrees is 2.0 radians?double d = Circle.radiansToDegrees(2.0);
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
13
Instance FieldsInstance Fields
public double r;• Each Circle object can have a have a radius
independent of other Circle objects• Outside a class, a reference to an instance field
must be pre-pended by a reference to the object that contains itCircle c = new Circle();c.r = 2.0;Circle d = new Circle();d.r = c.r;
Are they the same object?
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
14
Instance MethodsInstance Methods
• Instance methods operate on instances of a Class, and not on the Class itself
• E.g.– area()– circumference()
• If an instance method is used from outside the Class itself, it must be pre-pended by a reference to the instance to be operated on:– Circle c = new Circle();– c.r = 2.0;– double a = c.area();
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
15
Implementing InheritanceImplementing Inheritance
Circle
radius
circumferencearea
PlaneCircle
cxcy
isInside
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
16
““PlaneCircle” as a subclassPlaneCircle” as a subclasspublic class PlaneCircle extends Circle {
}
public double cx, cy;
public PlaneCircle(double r, double x, double y) { super(r); this.cx = x; this.cy = y;}
// automatically inherit fields and methods of Circle
PlaneCircle
cxcy
isInside
public boolean isInside(double x, double y) { …}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
17
Subclass ConstructorsSubclass Constructors
• In this case, the word “super”:– Invokes the constructor method of the superclass– Must only be used in this way within a constructor
method– Must apear within the first statement of the constructor
method
public PlaneCircle(double r, double x, double y) { super(r); // invoke constructor of superclass this.cx = x; // initialise instance field cx this.cy = y; // initialise instance field cy}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
18
Making more circlesMaking more circles
• PlaneCircle pc = new PlaneCircle(1.0, 0.0, 0.0);// Create a unit circle at the origin
• double a = pc.area( );// Calculate it’s area by invoking an inherited method
• boolean test = pc.isInside(1.5, 1.5); // Test if the point (1.5, 1.5) is inside the PlaneCircle pc or not
• What other methods might we want in PlaneCircle?
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
19
More robust ClassesMore robust Classes
• Declare fields as Private or Protected– Protected fields can be accessed by subclasses or
members of the same package
• Declare public “get” and “set” methods– with appropriate checks on the “set” methods
• E.g.public void setRadius(double radius) { checkRadius(radius);
this.r = radius; }
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
20
public class Circle { public static final double PI = 3.14159; // a constant protected double radius; protected void checkRadius(double radius) { if (radius < 0.0) { throw new IllegalArgumentException("radius must
not be negative"); } } public Circle(double radius) {
checkRadius(radius); this.radius = radius; } public double getRadius() {return radius;} public void setRadius(double radius) {
checkRadius(radius); this.radius = radius;
} public double area() {return PI*radius*radius; } public double circumference() {return 2*PI*radius; }}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
21
Java ExceptionsJava Exceptions• http://java.sun.com/docs/books/tutorial/essential/exceptions/
• The term exception is shorthand for the phrase "exceptional event."
• Definition: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
• Separating Error Handling Code from "Regular" Code .
• Some kinds-of Exception– Exception– ClassNotFoundException– IllegalAccessException– RuntimeException– Illegal ArgumentException– …
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
22
Catching ExceptionsCatching Exceptions
• Use the following construction:try {
// code that may throw exceptions}
catch (AnException e1) { // Code to handle this kind of exception
}
finally {// Code that will always execute
}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
23
Trying to succeedTrying to succeed
try {
// Normally this block of code will be
// executed successfully.
// However, if an exception is thrown
// execution will stop and the interpreter
// will attempt to find an appropriate
// “catch” statement.
}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
24
Catching ExceptionsCatching Exceptions
• There may be several “catch” blocks for different kinds of exceptions
catch (AnException e1) { // This block will be invoked if an // AnException kind of exception is // thrown, or a sub-type of AnException.// The block can refer to the exception// object by its name “e1”
}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
25
And FinallyAnd Finally
finally {
// This block contains code that will always be run
// even if control leaves the “try” block
// because of a return, continue or
// break statement.
// It will , however, be skipped if there is a
// System.exit( ) clause in the “try” block
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
26
Try…Catch…FinallyTry…Catch…Finally
try {
checkRadius(radius);
}
catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
finally{
System.out.println("Finally Here");
}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
27
Java AppletsJava Applets
• Java applications are executed from the command line
• Applets are small applications that can be embedded in html pages
• They can then be downloaded via the world wide web and invoked in a browser
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
28
Template for an AppletTemplate for an Applet
• Subclass one of the Java foundation classes:– java.applet.Applet;– javax.swing.JApplet;
• It’s behaviour is invoked in a “paint” method, not a “main” method
// File: MyApplet.javaimport java.awt.*;import java.applet.Applet;public class MyApplet extends Applet { public void paint(Graphics g) {
// Do something interesting}
}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
29
Viewing Area of AppletViewing Area of Applet
y
x(0,0)
height
width
These dimensions are set in the HTML file
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
30
Contract for the Contract for the paintpaint method method
• Dimensions of the region on the Web page assigned to the applet are set within an <applet> tag in an HTML file. (width & height)
• The paint( ) method defines the appearance of the applet within this rectangular region
• The paint( ) method is invoked when the applet is initially loaded in the browser (or applet viewer)
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
31
HelloFromVenus.javaHelloFromVenus.java
import java.awt.*;
import java.applet.Applet;
public class HelloFromVenus extends Applet {
public void paint(Graphics g) {
Dimension d = getSize( );
g.setColor(Color.black);
g.fillRect(0, 0, d.width, d.height);
}
}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
32
painting the textpainting the textpublic void paint(Graphics g) {
Dimension d = getSize( );
g.setColor(Color.black);
g.fillRect(0, 0, d.width, d.height);
// set font style and size:-
g.setFont(new Font(“Sans-serif”, Font.BOLD, 24));
// change colour on paint brush:-
g.setColor(new Color(255, 215, 0));
g.drawString(“Hello from Venus!”, 40, 25);
}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
33
finally add the imagefinally add the imagepublic void paint(Graphics g) {
Dimension d = getSize( );
g.setColor(Color.black);
g.fillRect(0, 0, d.width, d.height);
g.setFont(new Font(“Sans-serif”, Font.BOLD, 24);
g.setColor(255, 215, 0);
g.drawString(“Hello from Venus!”, 40, 25);
g.drawImage(getImage(getCodeBase( ), “Venus.gif”), 20, 60, this);
}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
34
Shifting graphical objects in AppletShifting graphical objects in Applet
• To translate a graphical object, use:– translate(xpos, ypos);
• To rotate a graphical object, use:– rotate(angle_in_radians);
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
35
Shifting graphical objects in AppletShifting graphical objects in Applet
public void paint(Graphics gg) {int ii;Graphics2D g = (Graphics2D) gg;g.setFont( new Font("Arial", Font.BOLD, sizeV) );g.setColor(Color.blue)g.translate(200, 200);for(ii = 1; ii <= 16; ii++){ g.rotate(Math.PI/8.0); g.drawString(textV, 20, 0);}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
36
Embedding Applets in HTMLEmbedding Applets in HTML
<HTML><HEAD> <TITLE>HelloFromVenus Applet</TITLE></HEAD><BODY BGCOLOR=BLACK TEXT=white><CENTER> <H2>Here is the <EM>Hello From Venus</EM> Applet</H2> <APPLET CODE="HelloFromVenus.class" WIDTH=300 HEIGHT=350> </APPLET></CENTER> Venus photo courtesy of NASA.</BODY>
</HTML>
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
37
Parameter passingParameter passing
• To make applets reusable in different contexts, we need to be able to pass parameters from the html files
• Can do this by using:– <param name> tag in html, and– getParameter(String) method in the
applet
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
38
Parameter passingParameter passing
• In HTML file:<applet code=bytecode-filename width=pixels height=pixels><param name=String value=String>
</applet>
• In Applet:String input = getParameter(String);
• Example:– HTML: <param name=“text” value=“Web Technology”>– String textV = getParameter(“text”);
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
39
Initialisation of an appletInitialisation of an applet
• Initialisation of an applet is not done in the Constructor method, but in an init( ) method
• An applet context interprets the <applet> tag in an html file
• The applet context first constructs an instance of the applet, then interprets the remaining parameters in the <applet> tag
• The init( ) method is invoked after the information in the <applet> tag has been processed
• Why?
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
40
Animated appletsAnimated applets
• Create a thread for an instance of the applet• paint( ) the applet into the applet
context
• Each time the relevant graphical properties of the applet are changed, repaint( ) the applet
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
41
Applet LifecycleApplet Lifecycle
• init() is invoked when the applet is loaded
• start() is invoked when the page containing the applet has been entered
• stop() is invoked when the page is left• destroy() is invoked when the page is
discarded
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
42
Using Scripts to Invoke a MethodUsing Scripts to Invoke a Method
• Give a name to the <applet> tag or ID to the <object> tag.
• Within the JavaScript, access the method by using the document object, then the applet name (OJECT ID), then the method name itself.
• Method must be declared as public.• Update the area by calling the repaint()
method.
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
43
Callbacks & EventsCallbacks & Events
• Callbacks are used in procedural libraries when they need to handle asynchronous events
• The alternative is for the client to continuously poll the library for events– This is inefficient, especially if a large number of
library components are registered with a client
• But the use of callback means a client may observe “intermediate” states of a library– “Classically” a library’s operations would run to
completion before returning control
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
44
Call SequenceCall Sequence
Client aUser Library
Client installs callback
Third party calls library
Library invokes callback“I need to tell you something!”
“What’s happened?”
“He’s changed a name!” Callback queries library
“That’s cool” Callback returns
Library returns
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
45
Java EventsJava Events
• An “Event” encapsulates information about some state change in its source– Pressing a button, Entering text in a text field …– Moving a slider on a scroll bar, …
• Events need not be generated by users:– Expiration of a timer, Arrival of incoming data, …
• The firing of an event is a way of one object telling one or more other recipients that something interesting has happened– The sender fires an event– A recipient is called a listener and handles the event
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
46
Java Event ModelJava Event Model
Event SourceEvent Source
Event ListenerEvent Listener
Register Event Listener
Fire Event
EventObject
EventObject
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
47
Java Event ObjectsJava Event Objects
• Encapsulates information specific to an instance of an event
• E.g. a “mouse click” event may contain:– The position of the mouse pointer– Which mouse button was clicked (and how
many times)
• The event object is passed as a parameter to the event notification method
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
48
Event SourcesEvent Sources
• Objects that fire events
• Implement methods that allow listeners to:– Register their interest in the events they
generate;– Unregister their interest in the events they
generate.
• Multicast event delivery enables an event to be fired to a number of event-listeners
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
49
Event ListenersEvent Listeners
• These are objects that need to be notified when a certain event occurs
• Event notifications are made through method invocations in the listening object– The event object is passed as a parameter– The event source must know which listener
object(s) to call
• This information is contained in an event-listener interface
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
50
Reuse the Applet ExampleReuse the Applet Exampleimport java.applet.*;import java.awt.*;import java.awt.event.*;public class simpleApplet extends Applet implements
ActionListener {private Button clickButton;private int buttonCount;
public void init() {clickButton = new Button("Click here");add(clickButton);buttonCount = 0;clickButton.addActionListener(this);
}public void actionPerformed(ActionEvent ae) {
buttonCount++;showStatus("Click total = " + buttonCount);
}}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
51
Event SummaryEvent Summary
EventObject
source
getSource()toString()
EventListener
notification(evt)
EventSource
addListener()removeListener()
fires passed to
registers 0..*
invokes notifications in 0..*
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
52
Event SummaryEvent Summary
• The components of a software product must interact to achieve a goal
• In general, it is hard to identify a single component that has overall control
• So a general model is for components to interact by triggering “Events” that other components register an interest in
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
53
PackagesPackages
• Packages create a grouping for related interfaces and classes.
• Packages can have types and members that are available only within the package.
• Packages make both small and large scale development easy to manage.
• Avoid potential name collision.
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
54
PackagesPackages• Here’s a simple example of the creation of a
package in a Java source file:package myFirstPackage;public class MyPublicClass extends ItsSuperclass {
//. . .}
• Package statement must be the first thing in that file (except for comments and white space, of course).
• Another class in package myFirstPackagepackage myFirstPackage.mySecondPackage;public class MySecondPublicClass extends ItsSuperclass {
//. . .}
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
55
PackagesPackages
• Each Java class should be located in a separate source file, the grouping of classes provided by a hierarchy of packages is analogous to the grouping of files into a hierarchy of directories on your file system.
./myFirstPackage/MyPublicClass.class
./myFirstPackage/mySecondPackage/MySecondPublicClass.class
• Both the compiler and the interpreter expect (and enforce) the hierarchy.
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
56
PackagesPackages
• Import packages & useimport myFirstPackage.mySecondPackage.*
import myFirstPackage.mySecondPackage.MySecondPublicClass
MySecondPublicClass mspc = new MySecondPublicClass();
• All import statements must appear after any package statement but before any class definitions. Thus, they are “stuck” at the top of your source file.
• * does NOT mean import recrusively
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
57
Java API:: java.lang.StringJava API:: java.lang.String
• Java strings are standard objects with built-in support.• String objects are read-only• Java also provides StringBuffer class for mutable
strings• Two basic method: length and charAt• indexOf(…) and lastIndexOf(…)String str=“Hello World”;int len = str.length;char c = str.charAt(1);int idx = str.indexOf(“ll”);int lidx = str.lastIndexOf(“l”);
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
58
Java API:: java.lang.StringJava API:: java.lang.String
• String Comparisons– regionMatches(…)– compareTo(…)– compareToIgnoreCase(…)– contentEquals(StringBuffer sb)– equals(…)– equalsIgnoreCase(…)
• Simply use + operator to concatenate strings.
• Use StringBuffer.
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
59
Java API:: java.lang.StringBufferJava API:: java.lang.StringBuffer
• String str = str1+str2+…+str100;• String str = new StringBuffer().append(str1)………append(str100).toString();
• insert(…)• replace(…)• setCharAt(…)
13th February 2004 Sifei HE © 2004
Introduction to JavaIntroduction to Java
60
Thank You!Thank You!
• Questions???
• Comments!!!