Introduction to JAVA.ppt

上传人:花仙子 文档编号:372929 上传时间:2018-10-04 格式:PPT 页数:76 大小:166.50KB
下载 相关 举报
Introduction to JAVA.ppt_第1页
第1页 / 共76页
Introduction to JAVA.ppt_第2页
第2页 / 共76页
Introduction to JAVA.ppt_第3页
第3页 / 共76页
Introduction to JAVA.ppt_第4页
第4页 / 共76页
Introduction to JAVA.ppt_第5页
第5页 / 共76页
亲,该文档总共76页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述

1、Introduction to JAVA,CMSC 331,Spring 1999,Introduction,Present the syntax of Java Introduce the Java API Demonstrate how to build stand-alone Java programs Java applets, which run within browsers e.g. Netscape Example programs tested using Java on Windows 98 and/or SGI,Features of Java,Object-orient

2、ed programming language clean, simple syntax similar to C, but without complexity of C+ Comprehensive API (application program interface) platform independence useful classes and methods,Building Standalone JAVA Programs (on UNIX),Prepare the file foo.java using an editor Invoke the compiler: javac

3、foo.java This creates foo.class Run the java interpreter: java foo,Java Virtual Machine,The .class files generated by the compiler are not executable binaries so Java combines compilation and interpretation Instead, they contain “byte-codes” to be executed by the Java Virtual Machine other languages

4、 have done this, e.g. UCSD Pascal This approach provides platform independence, and greater security,HelloWorld (standalone),public class HelloWorld public static void main(String args) System.out.println(“Hello World!“); ,Note that String is built in println is a member function for the System.out

5、class,Applets,The JAVA virutal machine may be executed under the auspices of some other program, e.g. a Web browser. Bytecodes can be loaded off the Web, and then executed locally. There are classes in Java to support this,Building Applets,Prepare the file foo.java, and compile it to create foo.clas

6、s Invoke an Applet Viewer, or a Java-aware browser such as Netscape, and open an HTML file such as foo.html Browser invokes the Java Virtual Machine,HelloWorld.java,import java.applet.*;public class HelloWorld extends Applet public void init() System.out.println(“Hello, world!“); ,hello.html,Hello,

7、World Hello, World,Data Types in Java,Primitive data types similar to C boolean true and false char 16 bits UNICODE byte, short, int, long integers; 8, 16, 32 and 64 bits respectively float and double IEEE 754,Array Allocation,Declared in two ways: float Vector1 = new float500; int Vector2 = 10, 20,

8、 30, 40; Not allocated on stack, but dynamically Are subject to garbage collection when no more references remain so fewer memory leaks Java doesnt have pointers!,Array Operations,Subscripts start at 0 as in C Subscript checking is done automatically Certain operations are defined on arrays of objec

9、ts, as for other classes e.g. Vector1.length = 500,Echo.java,C:UMBC331javatype echo.java / This is the Echo example from the Sun tutorial class echo public static void main(String args) for (int i=0; i javac echo.javaC:UMBC331javajava echo this is pretty silly this is pretty sillyC:UMBC331java,JAVA

10、Classes,The class is the fundamental concept in JAVA (and other OOPLs) A class describes some data object(s), and the operations (or methods) that can be applied to those objects Every object and method in Java belongs to a class,Syntax Notes,No global variables class variables and methods may be ap

11、plied to any instance of an object methods may have local (private?) variables No pointers but complex data objects are “referenced” Other parts of Java are borrowed from PL/I, Modula, and other languages,Example: FIFO,To show how simple data structures are built without pointers, well build a doubl

12、y-linked list ListItem class has some user data first refers to that ListItem object at the front of the queue last refers to the object at the end of the queue, i.e. most recently added,public class ListItem / In file ListItem.javapublic Object x; / N.B. a heterogeneous queuepublic ListItem previou

13、s;public ListItem next;/ Constructor operation takes initial valuepublic ListItem(String val) / this refers to “current” objectthis.x = val;this.previous = this.next = null;public boolean equals(ListItem c) / two ListItems are equal if their string values / are equal and they point to the same objec

14、tsreturn ( x.equals(c.x) ,import java.applet.*; / overview of fifo.javapublic class fifo extends Applet private int count = 0;public ListItem first = null; / first is the next item to be removedpublic ListItem last = null; / last is the item most recently added/ Called to initialize and test the app

15、let. More detail on next page.public void init() System.out.println(“isEmpty returns “+isEmpty();putQueue(“node 1“);.getQueue().printItem();./ See if the queue is emptypublic boolean isEmpty() . / Add an item to the queuepublic void putQueue(String value) . / Get the first item off the front of the

16、queuepublic ListItem getQueue() . ,/ Called to initialize and test the applet.public void init() System.out.println(“isEmpty returns “+isEmpty();putQueue(“node 1“);System.out.println(“First node is “); first.printItem();System.out.println(“Last node is “); last.printItem();putQueue(“node 2“);System.

17、out.println(“First node is “); first.printItem();System.out.println(“Last node is “); last.printItem();getQueue().printItem();System.out.println(“First node is “); first.printItem();System.out.println(“Last node is “); last.printItem();getQueue().printItem();System.out.println(“isEmpty returns “+isE

18、mpty();,/ See if the queue is emptypublic boolean isEmpty() return (count = 0); / Add an item to the queuepublic void putQueue(String value) ListItem newItem = new ListItem(value);if ( isEmpty() ) / Special case of empty queuefirst = last = newItem; else / next is the next item in the queue/ previou

19、s is the item (if any) that was in the / queue right ahead of this (current) itemlast.next = newItem;newItem.previous = last;last = newItem;count+;,/ Get the first item off the front of the queuepublic ListItem getQueue() ListItem firstItem = first;/ Make sure the queue isnt emptyif (isEmpty() ) Sys

20、tem.out.println(“Called getQueue on an empty queue“); else this.first = firstItem.next;/ Did we just remove the only item in the queue?if (first = null) last = null; else first.previous = null;count-;return firstItem;,Programming by Contract,Note that the integer variable count, and first and last (

21、both of type ListItem, are redundant in that first and last are null iff count = 0 first = last , but both not null iff count = 1 otherwise first != last iff count 1 Java has no assert macro, but we can test and throw an exception.,/ See if the queue is empty/ Check consistency of count, first and l

22、ast/ Note that exceptions are first-class objectsclass CorruptFifoException extends Exception;.public boolean isEmpty() if (count = 0) if (first = null else / count != 0.,Java vs. C+,Lots of similarity to C+ expressions (, operator okay only in loops) control structures same, except breaks and conti

23、nues may have labels, e.g. to escape from switch statements Java has single inheritance Java doesnt do templates,Single Inheritance, but,A class may extend only one class, but it may implement many others A subclass inherits the variables and methods of its superclass(es), but may override them Over

24、rides the methods defined in the class(es) it implements, as in upcoming thread example,Packages,Classes may be grouped into packages Six packages come with Java Packages add functionality without extending the language per se The import statement lets you use a method without its package name, e.g.

25、 import java.applet.* provides Applet class,Classes and Interfaces,The methods of an abstract class are implemented elsewhere A final class cannot be extended Instances of a synchronizable class can be arguments of a synchronize block Which means that access to “critical sections” is restricted,Visi

26、bility of Methods,Methods in a public class can be used outside. The file foo.java must contain exactly one public class: public class foo Methods in a private class can be used only within a file Default: class is accessible within current class package,Applets vs. Stand-alone,Applets have many res

27、trictions, which can be relaxed! no system calls limited network access after local file system is touched many others,Exceptions,Exceptions are objects in their own right They can be generated, caught and handled under program control Examples: IOException, ArithmeticException, etc.,try/catch/final

28、ly,Associates a set of statements with one or more exceptions and some handling code,try Thread.sleep(200); catch(InterruptedException e) System.out.println(e); finally System.out.println(“Wakeup”); ,A Tour of the Java API,An API Users Guide, in HTML, is bundled with Java Much of the “learning curve

29、” is in the API Lets look at some packages,The Java API,java.applet Applet class java.awt Windows, buttons, mouse, etc. java.awt.image image processing java.awt.peer GUI toolkit,java.io System.out.print java.lang length method for arrays; exceptions sockets java.util System.getProperty,The package

30、java.lang,The class Object The root class in Java Example methods: clone(), equals(), toString() Subclasses may override these methods The class Class Example methods: getName(), getSuperClass(),Observing an objects class,void printClassName (Object obj) System.out.println(“The class of “ + obj +“ i

31、s “ + obj.getClass().getName(); ,Strings in Java,Many methods defined in class java.lang: Several constructors concat(), equals(), indexOf(), length() Strings are immutable (why?) strings are concatenated with +,StringBuffers in Java,Several methods defined in class java.lang: Constructors can speci

32、fy length or initial value append(), insertf(), length(), toString(),Java.lang.system,Printstreams System.out.err(“Error message”); Inputstreams System.in.read(inputCharacter) System.in.read(inputBuffer, 0, maxChars),The Cloneable Interface,A class implements the cloneable interface by overriding th

33、e Object method clone() For example, we could add a clone() method to the FIFO class, if we wanted to be able to make copies of queues.,The class java.util,Interface to host OS Some basic functions and data structures BitSet, Dictionary (the superclass of Hashtable), Stack, Vector Random number gene

34、ration,System Properties,System properties are like UNIX environment variables, but platform independent The API class java.util has methods for accessing the system properties,/ determine environment variables import java.util.*; class envSnoop public static void main ( String args ) Properties p;S

35、tring s;p = System.getProperties();p.list(System.out);s = System.getProperty(“user.name“);System.out.println(“user.name=“+s);s = System.getProperty(“user.home“);System.out.println(“user.home=“+s); ,C:UMBC331javajava envSnoop - listing properties - java.specification.name=Java Platform API Specificat

36、ion awt.toolkit=sun.awt.windows.WToolkit java.version=1.2 java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment user.timezone=America/New_York java.specification.version=1.2 java.vm.vendor=Sun Microsystems Inc. user.home=C:WINDOWS java.vm.specification.version=1.0 os.arch=x86 java.awt.fonts= java.ve

37、ndor.url=http:/ user.region=US file.encoding.pkg=sun.io java.home=C:JDK1.2JRE java.class.path=C:Program FilesPhotoDeluxe 2.0Adob. line.separator=java.ext.dirs=C:JDK1.2JRElibext java.io.tmpdir=C:WINDOWSTEMP os.name=Windows 95 java.vendor=Sun Microsystems Inc. java.awt.printerjob=sun.awt.windows.WPrin

38、terJob java.library.path=C:JDK1.2BIN;.;C:WINDOWSSYSTEM;C:. java.vm.specification.vendor=Sun Microsystems Inc. sun.io.unicode.encoding=UnicodeLittle file.encoding=Cp1252 java.specification.vendor=Sun Microsystems Inc. user.language=en user.name=nicholas java.vendor.url.bug=http:/ java.vm.name=Classic

39、 VM java.class.version=46.0 java.vm.specification.name=Java Virtual Machine Specification sun.boot.library.path=C:JDK1.2JREbin os.version=4.10 java.vm.version=1.2 java.vm.info=build JDK-1.2-V, native threads, symcjit piler=symcjit path.separator=; file.separator= user.dir=C:UMBC331java sun.boot.clas

40、s.path=C:JDK1.2JRElibrt.jar;C:JDK1.2JR. user.name=nicholas user.home=C:WINDOWSC:UMBC331java,Java GUI,The awt class allows you to create frames buttons menus and menubars checkboxes text areas scrolling lists,GUI Examples,“Hello World”, revisited The Scribble example Both examples adapted from Flanag

41、ans “Java in a Nutshell”, first edition,import java.applet.*; import java.awt.*;public class SecondApplet extends Applet static final String message = “Hello World“;private Font font;/ One-time initialization for the appletpublic void init() font = new Font(“Helvetica“, Font.BOLD, 48);/ Draw the app

42、let whenever necessary. / Do some fancy graphics.public void paint(Graphics g) / The pink ovalg.setColor(Color.pink);g.fillOval(10, 10, 330, 100);,/ The red outline. java doesnt support wide lines, so we / try to simulate a 4-pixel wide line by drawing four ovalsg.setColor(Color.red);g.drawOval(10,1

43、0, 330, 100);g.drawOval(9, 9, 332, 102);g.drawOval(8, 8, 334, 104);g.drawOval(7, 7, 336, 106);/ The textg.setColor(Color.black);g.setFont(font);g.drawString(message, 40, 75); ,Scribble,Graphics objects can be added to applets, e.g. buttons and menus Events, such as mouse clicks, are handled,import j

44、ava.applet.*; import java.awt.*;public class Scribble extends Applet private int last_x = 0;private int last_y = 0;private Color current_color = Color.black;private Button clear_button;private Choice color_choices;/ Called to initialize the applet.public void init() / Set the background colorthis.se

45、tBackground(Color.white);/ Create a button and add it to the applet./ Also, set the buttons colorsclear_button = new Button(“Clear“);clear_button.setForeground(Color.black);clear_button.setBackground(Color.lightGray);this.add(clear_button);,/ Create a menu of colors and add it to the applet./ Also s

46、et the menus colors and add a label.color_choices = new Choice();color_choices.addItem(“black“);color_choices.addItem(“red“);color_choices.addItem(“yellow“);color_choices.setForeground(Color.black);color_choices.setBackground(Color.lightGray);this.add(new Label(“Color:“);this.add(color_choices);,/ C

47、alled when the user clicks the mouse to start a scribblepublic boolean mouseDown(Event e, int x, int y) last_x = x;last_y = y;return true;/ Called when the user scribbles with the mouse button downpublic boolean mouseDrag(Event e, int x, int y) Graphics g = this.getGraphics();g.setColor(current_colo

48、r);g.drawLine(last_x, last_y, x, y);last_x = x;last_y = y;return true;,/ Called when the user clicks the button or chooses a colorpublic boolean action(Event event, Object arg) / If the Clear button was clicked, handle itif (event.target = clear_button) Graphics g = this.getGraphics();Rectangle r =

49、this.bounds();g.setColor(this.getBackground();g.fillRect(r.x, r.y, r.width, r.height);return true;/ Otherwise if a color was chosen, handle thatif (event.target = color_choices) if (arg.equals(“black“) current_color=Color.black;else if (arg.equals(“red“) current_color=Color.red;else if (arg.equals(“yellow“) current_color=Color.yellow;return true;/ Otherwise let the superclass handle the eventelse return super.action(event, arg); ,

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 教学课件 > 大学教育

copyright@ 2008-2019 麦多课文库(www.mydoc123.com)网站版权所有
备案/许可证编号:苏ICP备17064731号-1