Download Java

Document related concepts
no text concepts found
Transcript
Object-Oriented Programming (Java)
September 2011
Course Information
• Lecturer: 熊运余
• Contact:
– [email protected], 85372698
• Course website:
– http://swjx.scu.edu.cn/moodle
•
2
3
CTE Curriculum
1: Introduction to
Information Systems
2: Introduction to
Computer Systems
4 : User Centered
Design and Testing
3: Object Oriented
Programming and
Design
7: Database
Systems
5: Data Structures
and Algorithms
6: System Level
Programming
9: Software
Specification, Test
and Maintenance
10: Software
Project Organization
and Management
8: Networks and
Distributed
Computing
4
Schedule
• 学时:80学时
• 课堂教学:32学时 ,实验:48学时
5
Contents
•
•
•
•
•
•
Java Application Basic (3 weeks)
Class design and implementing (6 weeks)
Advanced class design (2 weeks)
File I/O and GUI(3 week)
Design Pattern(2 weeks)
Java Advanced Tech (1 week)
6
Emphases
• Object Oriented concepts including inheritance,
polymorphism, abstract classes, and interfaces
• Object Oriented Designs using UML
• Advanced Java Class
7
Assessment
• 50% Final Examination;
• 50% On-class laboratory practice and homework.
8
Attendance, Late Work, Repeat Work
• Attendance:
– Absences need not be excused.
• Late Work:
– It is generally not accepted and receives a zero.
– In the case of unplanned emergencies, speak to the
instructor for a revised due date.
• Repeat Work (Retakes):
– The course will not give makeup.
– Multiple-choice assessments can be retaken for a
higher grade.
9
Your Role – Learning With Doing
• Attend all lectures
• Attend all laboratory classes
• Work out the exercise on your own or after a
discussion with your group, don’t make copy
• Come to see me during lecture, consultation hour
and laboratory session
10
You end up learning more in less
time when you are actually doing
stuff instead of just reading.
Reference Book & Course Material
• Deitel & Deitel, Java How To Program, Six
Edition.
• Thinking in Java, Bruce Eckel
• http://java.sun.com (Oracle)
• http://java.sun.com/docs/books/tutorial/
12
Topics Covered Today
• Unit 1.1 Java Applications
– 1.1.1 Applications in Java
13
1. Java Basic
• JAVA source code is first written in plain text files
ending with the .java extension.
• Those source files are then compiled into .class
files by the Java compiler (javac).
– A .class file does not contain code that is native to your
processor;
– it instead contains bytecodes(字节码) -- the machine
language of the Java Virtual Machine.
• The Java launcher tool (java) then runs your
application with an instance of the Java Virtual
Machine.
14
JAVA Technology
15
Platform-Independent
16
The Java Platform
• The Java platform is a software-only platform
that runs on top of other hardware-based
platforms.
• The Java platform has two components:
– The Java Virtual Machine
– The Java Application Programming Interface (API)
17
Java Virtual Machine
• A Java Virtual Machine (JVM) enables a set of
computer software programs and data structures to use
a virtual machine model for the execution of other
computer programs and scripts. The model used by a
JVM accepts a form of computer intermediate
language commonly referred to as Java bytecode.
18
Java Platform
Platforms
J2SDK
J2EE
J2ME
Core/Desktop
Enterprise/Server
Mobile/Wireless
Application,Applet,
Swing, Awt
JSP/Servlet, EJB
Midlet (Cell Phone/PDA)
Borland JBuilder,
JCreator, or Text
Editor
IBM WebSphere, WSAD
BEA WebLogic, Workshop
Sun One Studio
Oracle JDeveloper
19
Nokia, Motorola,
Siemens SDK
JBuilder,Sun One
Studio
Difference between Java and C
• Java is derived from C
• Many of its syntactic characteristics are similar to C
• However, there are some huge differences
20
Expressions
• Arithmetic operators are the same:–
+, –, *, /, %, ++, ––
• Numerical type conversion is mostly the same
– Java spells out divide by zero, NaN (not a number, etc.)
– C & C++ are machine dependent
21
Relational Operators
• Relational operators work the same way but return
different results:–
>, >=, <, <=, ==, !=
• In Java, they return values FALSE and TRUE
• In C/C++, they return values 0 and 1
• In C/C++,
– a value of zero means false
– any value that is not zero means true
– E.g., 1, 5, -1000000, 3.14159, 6.626068 × 10-34
22
Conditional and Bitwise Operators
• Conditional execution operators are same in Java and
C/C++:–
||, &&, !
• Bitwise operators are same in Java and C/C++:–
|, &, ^ for bit-by-bit operations with a word
• Shift operators differ a little bit
<< (left shift) is the same
>> (right shift) is machine dependent in C/C++
• I.e., whether to fill from left with zeros or sign bits
23
Assignment and Unary Operators
• Assignment operators work the same:–
=, +=, -=, *=, /=, &=, |=, ^=
• The following unary operators are available C/C++ but
not in Java
~
invert the bits of a word
*
pointer creation
&
pointer dereference
sizeof
# of bytes in operand or data type
->
pointer dereference with field selection
There is no pointer in Java.
24
Formatted Input & Output
• Very different between C and Java
• Very different between C and C++
• Handled by library functions in C
• printf()
• scanf()
• getc()
• putc()
• Many others!
25
printf() – Print formatted data
printf("string containing '%' specifiers",
expr1, expr2, expr3, …);
• Copy the string, character-by-character, to
the output.
• When the ith '%' is encountered, treat it as a
conversion specifier for converting the value
of expri
• Copy the converted value to the output per
instructions encoded in the conversion specifier
• Return number of characters printed
26
printf() conversion specifiers
• %d or %i
• Treat expression as a decimal number (with sign)
• %u
• Treat expression as unsigned decimal number
• %f
• Treat expression as double precision floating point number; print without
exponent
• %e or %E
• Treat expression as double precision floating point number; print with
exponent (base 10) — scientific notation
• %c
• Treat value of expression as the code for a single character
• %s
• Treat expression as a pointer to a string
• …
Later in this
course
27
printf() conversion specifiers (continued)
• Conversion specifiers may optionally contain
• Right or left alignment in the field
• Minimum field width (padded on right or left)
• Precision – i.e.,
– Maximum length of string
– Number of decimal places of floating point value
• Examples
%6d – print signed decimal number in 6-char field
%8.4f – print floating point number with four places after
decimal point, field width of 8 characters
28
scanf() – Scan formatted data
scanf("string containing '%' specifiers",
&var1, &var2, &var3, …);
• Scan the input, matching the string character by
character.
• When the ith '%' is encountered, treat as a
conversion specifier for converting next sequence
of characters and storing result in vari
• Copy the converted value to the output per instructions encoded
in the conversion specifier
• Stop if input does not match string or conversion
not successful
• Return number of successful conversions.
29
scanf() – Typical Usage
int j;
double x;
scanf("%d%f", &j, &x);
• Scan the input, skipping blanks and tabs
• Try to match a signed integer; if successful, store
result in j
• Continue scanning, skipping blanks and tabs
• Try to match a floating point number. If successful,
store in x
• Return number of items stored.
30
Primitive types
• In C, the primitive types are referred to using a combination of the
keywords char, int, float, double, signed, unsigned, long, short and
void. The allowable combinations are listed below, but their
meanings depend on the compiler and platform in use, unlike Java.
unsigned int
unsigned char
• Java primitive types
long (8bytes) int (4bytes) double (8bytes) float (4bytes)
boolean (true, false) char (2bytes)
31
Classes instead of structures
• C structure is like a Java class, and all parts are
visible to any code that knows the declaration.
• For example in C:
struct point
{
int x, y;
};
32
Type aliasing
• New names or aliases for existing types may be
created using typedef. For example:
typedef int int32_t;
There is no equivalent of type aliasing in Java.
33
Preprocessing
• There is no equivalent of preprocessing in Java
– Macro
#define PI 3.1415926
– Header file
#include "mydecls.h"
– Conditional compilation
#if
#else
34
Enumerations and Unions
• In C
enum light { RED, REDAMBER, GREEN, AMBER };
union number
{
char c;
int i;
float f;
double d;
};
• Java 1.5 has introduced a new enum family of
classes with greater type-safety, and a few other
nice facilities. Java does not have unions.
35
Global Variables
• In C
extern int giNumOfPoints;
• In Java
class Contour {
public static int iNumOfPoints;
}
usage of the variable: Contour.iNumOfPoints
There is no attribute definition outside class in Java. Java is a pure
object-oriented programming language. (attribute/method)
36
2. Applications in JAVA
• Java programs can be called from Web pages or
run stand alone.
– When launched from a Web page, the program is called
a Java “applet.” (JavaScript)
– When a non Web-based Java program is run on a user's
machine, it is a stand-alone Java "application."
– When running in a Web server, it is a Java "servlet."
(JSP/Servlet, JSF, Portlet, J2EE/EJB,Web Services,
JNLP)
37
Applications
• An application is a stand-alone program that runs
locally.
• Applications can use console I/O, or can have a
GUI developed using the Java class library.
• Applications have no system resource restrictions.
38
Running a Java Application
You write
Java code
using an
editor
Text Editor
Java code:
MyProg.java
You run the
Java
compiler
'javac'
You execute the
bytecode with the
command 'java'
javac MyProg.java
You save the
file with a
.java
extension
Bytecode:
MyProg.class
This creates a
file of
bytecode with
a .class
extension
java MyProg
Output
39
Creating an Application
 Open "Notepad" (Start  Programs  Other  Notepad)
 Type this in:
 Save As
“MyApplication.java"
 Open a DOS Window
(Start  MS-DOS
Prompt)
public class MyApplication {
public static void main(String args[]) {
System.out.println(
"This is my first application!");
}
}
 Type javac myApplication.java
 If you type dir MyApplication.* you should see MyApplication.java and
MyApplication.class
If it gives an error check you typed it in exactly right.
40
Running the Program
In the DOS window type java MyApplication
D:\> java MyApplication
You should see
something like this:
This is my first application!
D:\>
41
What does it mean?
This line announces that the program
(class) can be run by anyone (public), is
called MyApplication.
This line declares a main method.
It has one input argument. The
operating system begins
execution by calling main.
public class MyApplication {
public static void main(String args[]) {
System.out.println(
“This is my first application!”);
}
}
This line tells the computer to
display some text ( a string) on
the screen.
This is what is displayed.
42
Java Applets
• An applet is a little Java program that can run
inside a Web browser.
• It typically shows up inside a rectangular area
(which may be transparent) on the browser screen.
43
Applet Restrictions
• Security issues are important, since the provider of an
applet may not be trustworthy.
• Applets can’t touch your system resources (file system,
OS, etc.), although some browsers give extra privileges to
“trusted applets”. For instance an Applet cannot:
–
–
–
–
–
Access local files
Delete local files
Run another program
Find out your name
Connect to another host
• Applets can be slow, since the whole thing must be
downloaded each time it’s run.
44
Running a Java Applet
You write Java
code using an
editor
Java code:
MyApp.java
Text Editor
You run the Java
compiler 'javac'
javac MyApp.java
You save the file
with a .html
extension
You write a
web page in
html using an
editor
Text Editor
You can view the applet with the
command 'appletviewer'
You save the file
with a .java
extension
This creates a file of
bytecode with a .class
extension
Bytecode:
MyApp.class
Web page:
MyApp.html
appletviewer MyApp.html
45
You can view the web
page from a web
browser
Web Browser
Window
Creating an Applet
 Open "Notepad" (Start  Programs  Other  Notepad)
 Type this in:
 Save As
“MyApplet.java"
 Open a DOS
Window (Start 
MS-DOS Prompt)
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet {
public void paint(Graphics g) {
 Type javac
MyApplet.java
g.drawString("This is an applet!\n", 10, 10);
}
}
 If you type dir MyApplet.* you should see MyApplet.java and
MyApplet.class
46
Creating the Web Page
In order to run an applet you have to embed it in a web page
using a special <applet> tag e.g:
<applet code="name.class" width=www height=hhh></applet>
Using Notepad type in the following
and save it as "Greetings.html":
Size of the applet
in pixels
<html>
<head>
<title>Greetings Applet</title>
</head>
<body>
<applet code=“MyApplet.class" width=300 height=200 ></applet>
</body>
</html>
47
Running the Program
In the DOS window type appletviewer Greetings.html
G:\> appletviewer Greetings.html
You should see
something like
this:
48
Running in a Web Browser
Open Greetings.html in browser such as Netscape, IE or
Firefox, you should see something like:
Title
Your
greeting
Message
49
What does it mean?
These 2 lines tell the computer to
include (import) two standard
libraries awt (Abstract Window
Toolkit) and applet.
This line announces that the
program (class) can be run
by anyone (public), is called
MyApplet and is an Applet.
This line declares
what follows in the {
} as a method called
paint.
import java.awt.*;
import java.applet.Applet;
public class MyApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World!", 50, 50);
}
}
This line tells the
computer to display
some text ( a string)
on the screen.
This is what is
displayed
50
This is where it is
displayed in pixels
across and down from
the top left hand corner
Things to remember
• Everything in Java is case sensitive - Paint is not the
same as paint.
• The file containing the source code must have the same
name as the class it contains and use the .java extension.
For instance: MyApplet should match the name of the
file MyApplet.java (not myApplication.java).
• Curly brackets { and } are used to group parts of the
program called blocks together. Blocks can be nested
inside other blocks but each { must be matched with a }.
• Most statements require a semi-colon ; at the end. A
statement can continue on the next line if necessary.
• Spaces are not important - it is recommended to indent
blocks for clarity.
51
Java Demos*
• http://worldwind.arc.nasa.gov/java/demos/
52
3. Java Coding Environment
• Getting and Installing Java SE
–
–
–
–
Java 2 Platform, Standard Edition 5.0 (Java SE 5.0 “Tiger”).
J2SE(TM) Development Kit Documentation 5.0
http://java.sun.com/javase/downloads/index.jsp
Java SE 6 “Mustang”
• Follow the SSD3 Appendix B to setup your coding
environment.
• Bookmark the Java SE API so you can always get to it
easily. Or, just bookmark the index page on Sun’s Java
Web site.
53
Discussion – Java Performance
• Programs written in Java have a reputation for being
slower and requiring more memory than those written in
some other languages. However, Java programs'
execution speed improved significantly with the
introduction of Just-in-time compilation in
1997/1998 for Java 1.1, the addition of language features
supporting better code analysis (such as inner classes,
StringBuffer class, optional assertions, etc.), and
optimizations in the Java Virtual Machine itself, such
as HotSpot becoming the default for Sun's JVM in 2000.
54