68
Object-Oriented Programming (Java) 2014.2.26

Object-Oriented Programming (Java) 2014.2.26

Embed Size (px)

DESCRIPTION

Object-Oriented Programming (Java) 2014.2.26. Course Information. Lecturer: 熊运余 Assist :张乾初 QQ1053240123 Contact: [email protected], 18980704280 Course website: http://cc.scu.edu.cn/2226.html 兴趣题目 JAVA 地图、移动互联网开发. QQ 交流群: 296340622. 2. CTE Curriculum. 1: Introduction to - PowerPoint PPT Presentation

Citation preview

Page 1: Object-Oriented Programming (Java) 2014.2.26

Object-Oriented Programming (Java)2014.2.26

Page 2: Object-Oriented Programming (Java) 2014.2.26

2

Course Information

• Lecturer: 熊运余 Assist :张乾初 QQ1053240123

• Contact:– [email protected], 18980704280

• Course website:– http://cc.scu.edu.cn/2226.html– 兴趣题目 JAVA 地图、移动互联网开发

QQ 交流群:296340622

Page 3: Object-Oriented Programming (Java) 2014.2.26

3

CTE Curriculum

1: Introduction to Information Systems

2: Introduction to Computer Systems

3: Object Oriented Programming and

Design

5: Data Structuresand Algorithms

6: System LevelProgramming

10: SoftwareProject Organization

and Management

9: Software Specification, Testand Maintenance

8: Networks and DistributedComputing

4 : User Centered Design and Testing

7: Database Systems

Page 4: Object-Oriented Programming (Java) 2014.2.26

4

Schedule

• 学时: 64 学时• 课堂教学: 32 学时 ,实验: 32 学时• 学分: 4 学分

Page 5: Object-Oriented Programming (Java) 2014.2.26

5

Contents

• Java Application Basic (2 weeks)

• Class design and implementing (4 weeks)

• Advanced class design (2 weeks)

• File I/O and GUI ( 2week)

• Design Pattern ( 3 weeks )• Java Advanced Tech (2 week)

Page 6: Object-Oriented Programming (Java) 2014.2.26

6

Emphases

• Object Oriented concepts including inheritance, polymorphism, abstract classes, and interfaces

• Object Oriented Designs using UML

• Advanced Java Class

• Design Pattern

• Practice

Page 7: Object-Oriented Programming (Java) 2014.2.26

7

Assessment

• 50% Final Examination;

• 50% On-class laboratory practice and homework.

Page 8: Object-Oriented Programming (Java) 2014.2.26

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. 

Lenovo User
补考
Lenovo User
迟到
Page 9: Object-Oriented Programming (Java) 2014.2.26

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

Page 10: Object-Oriented Programming (Java) 2014.2.26

You end up learning more in less time when you are actually doing

stuff instead of just reading.

Page 11: Object-Oriented Programming (Java) 2014.2.26

11

Reference Book & Course Material

• Beginning Java Objects_From Concepts to Code_Second Edition

• 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/

Page 12: Object-Oriented Programming (Java) 2014.2.26

12

Topics Covered Today

• Unit 1.1 Java Applications– 1.1.1 Applications in Java

Page 13: Object-Oriented Programming (Java) 2014.2.26

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.

Page 14: Object-Oriented Programming (Java) 2014.2.26

14

JAVA Technology

Page 15: Object-Oriented Programming (Java) 2014.2.26

15

Platform-Independent

Page 16: Object-Oriented Programming (Java) 2014.2.26

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)

Page 17: Object-Oriented Programming (Java) 2014.2.26

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.

Page 18: Object-Oriented Programming (Java) 2014.2.26

18

Java Platform

Platforms

J2SDK J2EE J2ME

Core/Desktop

Application,Applet, Swing, Awt

Enterprise/Server

JSP/Servlet, EJB

Mobile/Wireless

Midlet (Cell Phone/PDA)

Borland JBuilder, JCreator, or Text Editor

IBM WebSphere, WSAD

BEA WebLogic, Workshop

Sun One Studio

Oracle JDeveloper

Nokia, Motorola, Siemens SDK

JBuilder,Sun One Studio

Page 19: Object-Oriented Programming (Java) 2014.2.26

19

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

Page 20: Object-Oriented Programming (Java) 2014.2.26

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

Page 21: Object-Oriented Programming (Java) 2014.2.26

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

Very important!

Page 22: Object-Oriented Programming (Java) 2014.2.26

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

Page 23: Object-Oriented Programming (Java) 2014.2.26

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.

Lenovo User
一元符号
Lenovo User
一元
Page 24: Object-Oriented Programming (Java) 2014.2.26

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!

Page 25: Object-Oriented Programming (Java) 2014.2.26

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

Page 26: Object-Oriented Programming (Java) 2014.2.26

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

Page 27: Object-Oriented Programming (Java) 2014.2.26

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

Lenovo User
说明符
Page 28: Object-Oriented Programming (Java) 2014.2.26

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.

Page 29: Object-Oriented Programming (Java) 2014.2.26

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.

Page 30: Object-Oriented Programming (Java) 2014.2.26

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)

Page 31: Object-Oriented Programming (Java) 2014.2.26

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;

};

Page 32: Object-Oriented Programming (Java) 2014.2.26

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.

Page 33: Object-Oriented Programming (Java) 2014.2.26

33

Preprocessing

• There is no equivalent of preprocessing in Java– Macro

#define PI 3.1415926

– Header file#include "mydecls.h"

– Conditional compilation#if

#else

Page 34: Object-Oriented Programming (Java) 2014.2.26

34

Enumerations and Unions

• In Cenum 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.

Lenovo User
琥珀色的
Page 35: Object-Oriented Programming (Java) 2014.2.26

35

Global Variables

• In Cextern int giNumOfPoints;

• In Javaclass 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)

Page 36: Object-Oriented Programming (Java) 2014.2.26

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)

Page 37: Object-Oriented Programming (Java) 2014.2.26

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.

Page 38: Object-Oriented Programming (Java) 2014.2.26

38

Running a Java Application

You write Java code using an editor

javac MyProg.java

java MyProg

Java code: MyProg.java

Bytecode: MyProg.class

Text Editor

Output

You save the file with a .java extension

You run the Java compiler 'javac'

You execute the bytecode with the command 'java'

This creates a file of bytecode with a .class extension

Page 39: Object-Oriented Programming (Java) 2014.2.26

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)

Type javac myApplication.java

If it gives an error check you typed it in exactly right.

public class MyApplication { public static void main(String args[]) { System.out.println(

"This is my first application!"); }}

If you type dir MyApplication.* you should see MyApplication.java and MyApplication.class

Page 40: Object-Oriented Programming (Java) 2014.2.26

40

Running the Program

D:\> java MyApplication

In the DOS window type java MyApplication

You should see something like this: This is my first application!

D:\>

Page 41: Object-Oriented Programming (Java) 2014.2.26

41

What does it mean?

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 line declares a main method. It has one input argument. The operating system begins execution by calling main.

This line announces that the program (class) can be run by anyone (public), is called MyApplication.

This is what is displayed.

Page 42: Object-Oriented Programming (Java) 2014.2.26

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.

Page 43: Object-Oriented Programming (Java) 2014.2.26

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.

Lenovo User
值得信赖的
Page 44: Object-Oriented Programming (Java) 2014.2.26

44

Running a Java Applet

javac MyApp.java

appletviewer MyApp.html

Java code: MyApp.java

Bytecode: MyApp.class

Text Editor

Window

This creates a file of bytecode with a .class extension

You save the file with a .java extension

You write Java code using an editor

Web page: MyApp.html

Text EditorWeb Browser

You write a web page in html using an editor

You run the Java compiler 'javac'

You can view the applet with the command 'appletviewer'

You can view the web page from a web browser

You save the file with a .html extension

Page 45: Object-Oriented Programming (Java) 2014.2.26

45

Creating an Applet

Open "Notepad" (Start Programs Other Notepad)

Type this in:

Save As “MyApplet.java"

Open a DOS Window (Start MS-DOS Prompt)

Type javac MyApplet.java

import java.applet.*;import java.awt.*;

public class MyApplet extends Applet {

public void paint(Graphics g) {

g.drawString("This is an applet!\n", 10, 10); }}

If you type dir MyApplet.* you should see MyApplet.java and MyApplet.class

Page 46: Object-Oriented Programming (Java) 2014.2.26

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>

<html><head><title>Greetings Applet</title></head><body><applet code=“MyApplet.class" width=300 height=200 ></applet></body></html>

Using Notepad type in the following and save it as "Greetings.html":

Size of the applet in pixels

Page 47: Object-Oriented Programming (Java) 2014.2.26

47

Running the Program

G:\> appletviewer Greetings.html

In the DOS window type appletviewer Greetings.html

You should see something like this:

Page 48: Object-Oriented Programming (Java) 2014.2.26

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

Page 49: Object-Oriented Programming (Java) 2014.2.26

49

What does it mean?

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 line declares what follows in the { } as a method called paint.

This line announces that the program (class) can be run by anyone (public), is called MyApplet and is an Applet.

These 2 lines tell the computer to include (import) two standard libraries awt (Abstract Window Toolkit) and applet.

This is what is displayed

This is where it is displayed in pixels across and down from the top left hand corner

Page 50: Object-Oriented Programming (Java) 2014.2.26

50

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.

Lenovo User
区分大小写
Page 51: Object-Oriented Programming (Java) 2014.2.26

51

Java Demos*

• http://worldwind.arc.nasa.gov/java/demos/

Lenovo User
美国国家航空航天局(National Aeronautics and Space Administration)
Page 52: Object-Oriented Programming (Java) 2014.2.26

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.

Page 53: Object-Oriented Programming (Java) 2014.2.26

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.

Page 54: Object-Oriented Programming (Java) 2014.2.26

54

Java 简介 Java 简介

History– Java 语言之父 James Gosling

– 1992 年, Sun 公司的 FirstPerson 小组,开发手机、 PDA 应用软件,最初使用的是 C++ 语言。– 小组转移到交互式电视机机顶盒的开发, oak 语言,即 Java 的前身。– 1994 年, Internet 开始受到关注,需要一个小巧、健壮、平台无关的语

言, oak 改头换面成为 Java 。– 1996 年, Java 编译器的第一版发布。– 1997 年, Sun 公司推出 Java1.1 ( JDK1.0 )。– 1998 年, Sun 公司推出 Java2 ( JDK1.2 )。– 2004 年, J2SE1.5 发布,是 Java 语言发展史上的又一里程碑事件。为了表

示这个版本的重要性, J2SE1.5 更名为 J2SE5.0 。– 2005 年, J2SE6.0 发布 ; J2EE:Java EE;J2SE:Java SE;J2ME:Java ME.

– 2009 年 4 月, Sun 被甲骨文收购 , 其中包含 Java 技术 .

Page 55: Object-Oriented Programming (Java) 2014.2.26

55

Java 简介 Java 简介

Java 的特点◇ 分布式

– 数据分布和操作分布– Java 支持 B/S 计算模式– Java 提供了一整套网络类库

◇ 安全性、可靠性– 强类型语言– 摒弃了指针类型– GC 自动垃圾回收、异常处理机制、运行时检查

◇ 多线程

Page 56: Object-Oriented Programming (Java) 2014.2.26

56

Java 简介 Java 简介

Java 开发环境– 设置系统环境变量

JAVA_HOME= C:\Sun\AppServer\jdk ( JDK 的安装目录)

classpath += .;%JAVA_HOME%\lib\dt.jar;

%JAVA_HOME%\lib\tools.jar;

path += ;%JAVA_HOME%\bin

Page 57: Object-Oriented Programming (Java) 2014.2.26

57

Java 简介 Java 简介

JDK 的实用工具

○ 是一个基于命令行的调试工具,可以逐行执行程序,

设置断点和检查变量的值等。 Jdb [options] class

○ 是一种用于执行 HTML 文件上的 java 小程序的java 浏器。

Appletviewer [-debug] html 文件名

◇ Java 调试器

◇Applet 浏览器

Page 58: Object-Oriented Programming (Java) 2014.2.26

58

Java 简介 Java 简介

测试开发环境

Page 59: Object-Oriented Programming (Java) 2014.2.26

59

Java 简介 Java 简介

测试开发环境源文件: HelloJC.java

编译

Page 60: Object-Oriented Programming (Java) 2014.2.26

60

Java 简介 Java 简介

测试开发环境运行

Page 61: Object-Oriented Programming (Java) 2014.2.26

61

Java 简介 Java 简介

Java 的注释

– 两种注释风格/* */ : /* This is a comment that continue across lines */

// : //This is a one-line comment

○ 养成良好的编码风格,对代码多加注释

Page 62: Object-Oriented Programming (Java) 2014.2.26

62

Java 语言基础 Java 语言基础

Java 的标识符

– 标识符 字符数字序列。在 Java 语言里,标志符以字符或 _ , $ 开头,后面可以包含数字,标志符是大小写有区别的,没有长度限制。

示例 合法标志符: nVariable , $Variable , _Variable

非法标志符: 2007Variable , new , Interger

Page 63: Object-Oriented Programming (Java) 2014.2.26

63

Java 语言基础Java 语言基础

Java 的分隔符

– 分隔符用来使编译器确认代码在何处分隔

– ( ) [ ] { } ; , . 都是 Java 语言的分

隔符

– 例: i = p-k; //; 表示一行语句的结束

Page 64: Object-Oriented Programming (Java) 2014.2.26

64

Java 语言基础Java 语言基础

Java 的变量与常量

– 常量 在程序运行期间不能改变的量。 利用 final 关键字来定义常量。

○ 定义格式: final type name =

value;

例: final double PAI = 3.14 ;

Page 65: Object-Oriented Programming (Java) 2014.2.26

65

Java 语言基础Java 语言基础

Java 的基本数据类型– 字符类型

注意:字符串不属于简单数据类型,它被当作 Java 所提 供的 String 类的一个对象来处理。

字符 含义\’ 单引号字符\\ 反斜杠\r 回车\n 换行\f 走纸换页\t 横向跳格\b 退格

用单引号括 ( ‘ ’ ) 起来的一个字符常量,用双引号括 ( “ ” ) 起来的表示一个字符串。

示例: ‘ a ’, ‘ B ’

Page 66: Object-Oriented Programming (Java) 2014.2.26

66

运算符 使用方法 功能说明+ op1+op2 操作数 1 加操作数 2

- op1-op2 操作数 1 减操作数 2

* op1*op2 操作数 1 乘操作数 2

/ op1/op2 操作数 1 除操作数 2

% op1%op2 操作数 1 和操作数 2 的模

Java 语言基础Java 语言基础

–二元算术运算符

Java 的运算符

Page 67: Object-Oriented Programming (Java) 2014.2.26

67

操作符 使用方法 功能说明& op1&op2 按位与| op1|op2 按位或^ op1^op2 按位异或~ ~op1 按位取反

<< op1<<op2 op1左移 op2位>> op1>>op2 op1右移 op2位

>>> op1>>>op2 op1 无符号右移 op2位

Java 语言基础Java 语言基础

–位运算符

Java 的运算符

Page 68: Object-Oriented Programming (Java) 2014.2.26

68

Java 简介 Java 简介

Java 程序开发的生命周期