Object-Oriented Programming (Java) 2014.2.26 Course Information • Lecturer: 熊运余 Assist :张乾初 QQ1053240123 • Contact: – 3149102@qq.com, 18980704280 • Course website: QQ交流群: 296340622 – http://cc.scu.edu.cn/2226.html – 兴趣题目JAVA地图、移动互联网开发 2 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 3 Schedule • 学时:64学时 • 课堂教学:32学时 ,实验:32学时 • 学分:4学分 4 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) 5 Emphases • Object Oriented concepts including inheritance, polymorphism, abstract classes, and interfaces • Object Oriented Designs using UML • Advanced Java Class • Design Pattern • Practice 6 Assessment • 50% Final Examination; • 50% On-class laboratory practice and homework. 7 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. 8 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 9 You end up learning more in less time when you are actually doing stuff instead of just reading. 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/ 11 Topics Covered Today • Unit 1.1 Java Applications – 1.1.1 Applications in Java 12 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. 13 JAVA Technology 14 Platform-Independent 15 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) 16 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. 17 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 18 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 19 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 20 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 21 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 22 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. 23 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! 24 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 25 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 26 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 27 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. 28 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. 29 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) 30 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; }; 31 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. 32 Preprocessing • There is no equivalent of preprocessing in Java – Macro #define PI 3.1415926 – Header file #include "mydecls.h" – Conditional compilation #if #else 33 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. 34 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) 35 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) 36 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. 37 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 38 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. 39 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:\> 40 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. 41 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. 42 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. 43 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 44 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 45 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> 46 Running the Program In the DOS window type appletviewer Greetings.html G:\> appletviewer Greetings.html You should see something like this: 47 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 48 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 49 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. 50 Java Demos* • http://worldwind.arc.nasa.gov/java/demos/ 51 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. 52 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. 53 Java简介 History – Java语言之父 James Gosling – 1992年,Sun公司的FirstPerson小组,开发手机、 PDA应用软件,最初使用的是C++语言。 – 小组转移到交互式电视机机顶盒的开发,oak语言,即Java的前身。 – 1994年,Internet开始受到关注,需要一个小巧、健壮、平台无关的语言,oa k改头换面成为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技术. 54 Java简介 Java的特点 ◇ 分布式 – 数据分布和操作分布 – Java支持B/S计算模式 – Java提供了一整套网络类库 ◇ 安全性、可靠性 – 强类型语言 – 摒弃了指针类型 – GC 自动垃圾回收、异常处理机制、运行时检查 ◇ 多线程 55 Java简介 Java开发环境 – 设置系统环境变量 JAVA_HOME= C:\Sun\AppServer\jdk (JDK的安装目录) classpath += .;%JAVA_HOME%\lib\dt.jar; %JAVA_HOME%\lib\tools.jar; path += ;%JAVA_HOME%\bin 56 Java简介 JDK的实用工具 ◇ Java 调试器 ○ 是一个基于命令行的调试工具,可以逐行执行 程序, 设置断点和检查变量的值等。 Jdb [options] class ◇ Applet 浏览器 ○ 是一种用于执行HTML文件上的java小程序的java 浏器。 Appletviewer [-debug] html文件名 57 Java简介 测试开发环境 58 Java简介 测试开发环境 源文件:HelloJC.java 编译 59 Java简介 测试开发环境 运行 60 Java简介 Java的注释 – 两种注释风格 /* //: ○ */: /* This is a comment that continue across lines */ //This is a one-line comment 养成良好的编码风格,对代码多加注释 61 Java语言基础 Java的标识符 – 标识符 字符数字序列。在Java语言里,标志符以字 符或_ , $开头,后面可以包含数字,标志符是大小 写有区别的,没有长度限制。 示例 合法标志符:nVariable , $Variable , _Variable 非法标志符:2007Variable , new,Interger 62 Java语言基础 Java的分隔符 – 分隔符用来使编译器确认代码在何处分隔 – ( ) [ ] { } ; , . 都是Java语言的分隔符 – 例:i = p-k; //;表示一行语句的结束 63 Java语言基础 Java的变量与常量 – 常量 在程序运行期间不能改变的量。 利用final关键字来定义常量。 ○ 定义格式:final type name = value; 例:final double PAI = 3.14; 64 Java语言基础 Java的基本数据类型 – 字符类型 用单引号括( ‘ ’ )起来的一个字符常量, 用双引号括( “ ” )起来的表示一个字符串。 含义 示例:字符 ‘ a ’, ‘ B ’ \’ 单引号字符 \\ 反斜杠 \r 回车 \n 换行 \f 走纸换页 \t 横向跳格 \b 退格 注意:字符串不属于简单数据类型,它被当作Java所提 供的String类的一个对象来处理。 65 Java语言基础 Java的运算符 – 二元算术运算符 运算符 使用方法 功能说明 + op1+op2 操作数1加操作数2 - op1-op2 操作数1减操作数2 * op1*op2 操作数1乘操作数2 / op1/op2 操作数1除操作数2 % op1%op2 操作数1和操作数2的模 66 Java语言基础 Java的运算符 – 位运算符 操作符 使用方法 功能说明 & | op1&op2 op1|op2 按位与 按位或 ^ ~ << >> op1^op2 ~op1 op1<<op2 op1>>op2 按位异或 按位取反 op1左移op2位 op1右移op2位 >>> op1>>>op2 op1无符号右移op2位 67 Java简介 Java程序开发的生命周期 68