1 / 100

The Java Language and Environment

The Java Language and Environment. Cecilia Bastarrica, Anupama Vadali, and Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut 371 Fairfield Road, Box U-255 Storrs, CT 06269-2155. steve@engr.uconn.edu http://www.engr.uconn.edu/~steve

joie
Download Presentation

The Java Language and Environment

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. The Java Language and Environment Cecilia Bastarrica, Anupama Vadali, and Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut 371 Fairfield Road, Box U-255 Storrs, CT 06269-2155 steve@engr.uconn.edu http://www.engr.uconn.edu/~steve http://www.engr.uconn.edu/cse (860) 486 - 4818

  2. Overview of Presentation • Motivation and Introduction to Java • Designing and Developing Applets in Java • The Java User Interface - GUI with AWT • Designing and Developing Java Classes • Inheritance and Interfaces in Java • Polymorphism and Object Serialization

  3. Motivation and Introduction to Java • Java is Emerging as the OO Language of Choice • Java’s Utilization in … • Distributed Internet-Based Applications of All Types • Legacy/COTS Integration for Enterprise Computing • General-Purpose, Single-CPU Development • Significant Dissemination on WWW: • http://www.javasoft.com • http://www.gamelan.com • We’ll Overview Key Features and Capabilities

  4. An Overview of Java • Java is a Third Generation, General Purpose, Platform Independent, Concurrent, Class-Based, Object-Oriented Language and Environment • Java Composed of JDK and JRE • Java Language • Java Packages (Libraries) • javac Compiler to Bytecode (p-code) • JDB Java Debugger • Java Interpreter - Platform Specific • JDK: Java Development Environmenthttp://www.javasoft.com/products/jdk/1.2/ • JRE: Java Runtime Environmenthttp://www.javasoft.com/products/jdk/1.2/jre/index.html

  5. What is Java?Software Releases and IDEs • Java is Free! • Current Releases • Version 2 for Win95, Win98, NT • Version 2 (Early Access) for Solaris • Third-Party Ports to All Conceivable HW/SW Platforms from Micros to Mainframes http://www.javasoft.com/cgi-bin/java-ports.cgi • Integrated Development Environments (IDEs) • Commercial Products, Freeware, Visual IDEs • Visual J++, Visual Café, Kawa, Jpad, Javelin

  6. Java Virtual Machine (JVM) • JVM is a Platform Specific Program which Interprets and Executes Java Code • JVM Interprets and Executes Bytecodes • JVM Targeted as Small/Efficient - Embeddable within Consumer Electronics • JVM Stack Based Machine - Simulates Real Processor CA FE BA BE 00 03 00 2D 00 3E 08 00 3B 08 00 01 08 00 20 08

  7. Java Visualization

  8. Packages In Java • Allows Related Classes to be Grouped into a Larger Abstraction • Similar to Ada95 Packages • Unavailable in C++ • Utilization of Packages for SW Design and Development • Components, Modularization, Groupings • Enforcement by Compiler of Package Rules • Overall, Packages Enhance the Control and Visibility to Fine-Tune • Who Can See What When

  9. The Java API Packages • Application Programming Interface (API) • Java Defined - Building Blocks/Libraries • Java Platform 1.2/2 Core API java.applet java.rmi java.awt java.rmi.dgc java.awt.datatransfer java.rmi.registry java.awt.event java.rmi.server java.awt.image java.security java.beans java.security.acl java.io java.security.interfaces java.lang java.sql java.lang.reflect java.text java.math java.util java.net java.util.zip • Power of Java Contained with APIs

  10. The Java Language • Overview of Non-OO Capabilities • Based on C/C++ • No includes, typedefs, structures, groups • Unicode Character Set - 34,168 Characters • Automatic Coercions Not Supported • Strongly-Type Language • Variables in Java • Primitive Types: ints, floats, booleans, Unicode chars • Reference Types: arrays, classes, interfaces • No Physical Pointers in Java!

  11. The Java Language • Statements in Java - Resembles C and C++ • Assignment/Expressions and Precedence • for, while, do-while • if-then, switch-case • break, continue, label, return • Exception Handling • Similar to C++ • try, throws, catch Blocks • Strongly Integrated Throughout APIs

  12. The Java LanguageMotivating the Class Concept • Conceptually, Classes are Structures/Records with Functions that are Encapsulated structure Item { int UPC, OnShelf, InStock, ROLimit; char* Name; float RCost, WCost; Status Create_New_Item(int UPC, ...); NameCost* Get_Item_NameCost(int UPC); void Modify_Inventory(int UPC, int Delta) ; Boolean Check_If_On_Shelf(int UPC); Boolean Time_To_Reorder(int UPC); }; NameCost *nc; Item I1, I2; I1.Create_New_Item(...); nc = I2.Get_Item_NameCost(UPC);

  13. The Java LanguageObject-Oriented Features • Class - similar to C++ Class • Classes have Members (Methods and Variables) • Members Tagged Using Keywords • private: Typically, Inaccessible • public: Potential to be Accessible • protected: Accessible via Inheritance • package: Accessible within Package • Involve Visible Between Classes, Within Packages, and Due to Inheritance

  14. Classes in Java • A Supermarket Item • Keywords must be Utilized for Each Attribute or Method Declaration class Item { private String UPC, Name; private int Quantity; private double RetailCost; protected double WholeCost; public Item() { ... }; public void finalize() { ... }; public boolean Modify_Inventory(int Delta){...}; public int Get_InStock_Amt() {return Quantity;}; };

  15. Classes in Java class Item { private String UPC, Name; private int Quantity; private double RetailCost; protected double WholeCost; public Item() { ... }; public void finalize() { ... }; public boolean Modify_Inventory(int Delta) { int i = Get_InStock_Amt (); if (Delta >= 0) { Quantity += Delta; return true; } else { return false;} }; public int Get_InStock_Amt() {return Quantity;}; public double Compute_Item_Profit() {...}; protected boolean Modify_WholeSale(); {...}; };

  16. Visibility of Attributes/Methods • Class Members (Attributes and Methods) • Visibility Tags for Members • Private: Visible only to Class • Protected: Visible to Class and Other Classes within Package • Public: Visible to Class, Other Classes within Package, and if Class is Public, Visible to Other Packages/Classes • No Tag: Visible Only to Other Classes within Defining Package • Java's Controlled Sharing within/between Packages not Supported in C++ • Abstraction/Encapsulation Superior in Java!

  17. Inheritance - Two Roles • Controlled Sharing Between Classes • Generalization vs. Specialization • Treat Instances of Different Classes in a Uniform Fashion • Polymorphism and Dynamic Binding • Inheritance in Java Item / \ DeliItem ProduceItem | SaladItem class DeliItem extends Item { ... }; class SaladItem extends DeliItem { ... }; class ProduceItem extends Item { ... };

  18. Designing and Developing Applets in Java • Applets Small Independent Programs Intended for Embedding into WWW Pages and Executable via Java-Enabled Browser (Netscape or IE) • Applets Operate Under Severe Security Limits: • Can’t Execute Local Programs • Can’t Communicate with Host Other than one from Which Downloaded • Can’t Read/Write to Local File System • Can’t Find Information on Local System Except Java/OS Versions and Character/Line Separators

  19. Designing and Developing Applets in Java • An Applet is a Java Program that Executes as part of an HTML Page applet A.java HTML file ... <APPLET CODE = “A.class”> ... javac applet A.class

  20. Applets Inheritance Structure java.lang.Object java.awt.Component java.awt.Container java.applet.Applet your applet Everything in Java inherits from the Object class Event-handling and drawing capabilities Ability to hold components Limits what an Applet can and cannot do Every Applet is a subclass of the Applet class.

  21. Applet Methods Eligible for Overriding Methods for Milestones • init - initializes an applet when it is loaded • start - (re)starts applet’s execution • stop - stops applet’s execution • destroy - final cleanup before unloading Methods for Drawing • paint • update The applet subclass must override at least one of these methods: init, start or paint.

  22. Applets Handle Events by Implementing the Corresponding interface import java.awt.event.MouseListener; import java.awt.event.MouseEvent; … public class Simple extends Applet implements MouseListener { … public void init() { addMouseListener(this); … } public void mouseClicked(MouseEvent event) { addItem(“click…”); } … } Handling Events mouseClicked mouseEntered mouseExited mousePressed mouseReleased Protocol of behavior All methods in the interface must be implemented

  23. Running an Applet in HTML <APPLET CODE = “AppletSubclass.class” WIDTH = anInt HEIGHT = anInt> </APPLET> The Browser: • Reserves a Display Area for the Applet • Loads the bytecode • Creates an Instance of the Subclass • Calls the init and start Methods

  24. Loading an Applet • Finding an Applet • CODEBASE • Relative/Absolute Address CODEBASE=“example/” CODEBASE=“http://someServer/…/otherDirectory/” • Bringing the Applet • Class by Class/Archives otherDirectory example HTML file HTML file Class file Class file

  25. The <APPLET> tag <APPLET [CODEBASE = codebaseURL] (CODE = appletFile | OBJECT = serializedApplet) [ARCHIVE = archivesList] [ALT = alternateText] [NAME = appletInstanceName] WIDTH = pixelsHEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [<PARAMNAME = appletParameter1VALUE = value>] [<PARAMNAME = appletParameter2VALUE = value>] … [alternateHTML] </APPLET>

  26. Security Issues • An Untrusted Applet Cannot: • Load Libraries or Define Native Methods • Read or Write Files on the Host that is Executing the Applet • Make Network Connections Except to the Host from Which it was Loaded From • Start any Program on the Host that is Executing the Applet • Get Many System Properties

  27. Example of a GUI Applet /* http://java.sun.com/docs/books/tutorial/ui/components/example/ ButtonDemo.java */ import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.applet.Applet; public class ButtonDemo extends Applet implements ActionListener { Button b1, b2, b3; static final String DISABLE = "disable"; static final String ENABLE = "enable"; public void init() { b1 = new Button(); b1.setLabel("Disable middle button"); b1.setActionCommand(DISABLE); b2 = new Button("Middle button"); b3 = new Button("Enable middle button"); b3.setEnabled(false); b3.setActionCommand(ENABLE);

  28. Example of a GUI Applet (Continued) //Listen for actions on buttons 1 and 3. b1.addActionListener(this); b3.addActionListener(this); //Add Components to the Applet, using the default FlowLayout. add(b1); add(b2); add(b3); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command == DISABLE) { //They clicked "Disable middle button" b2.setEnabled(false); b1.setEnabled(false); b3.setEnabled(true); } else { //They clicked "Enable middle button" b2.setEnabled(true); b1.setEnabled(true); b3.setEnabled(false); } } }

  29. The Java User Interface - GUI with AWT • UI Refers to the Communications Between a Program and a User • Java Abstract Windowing Toolkit (AWT) and Swing Contains Complete Set of Classes for Writing GUI Programs • AWT Classes Categorized into: • GUI Components • Containers • Layout Managers • Drawing • Event Handling

  30. AWT Components • Button • CheckBoxes • Choices • Lists • Menus • Textfields • Text Areas • Labels

  31. Containers • The Java AWT Provides Three Types of Containers Implemented as Subclasses of Container Class: • Window • Frame - creates a normal full fledged window to contain components • Dialog - provides a window that is dependent on another window • FileDialog - helps the user to open and save file • Panel - Groups Components within an Area of an Existing Window • ScrollPane -Like Panel, Used to Display Large Component in a Limited Amount of Space

  32. Inheritance Hierarchies for Components

  33. Layout Managers • Layout Manager Controls the Size and Position of Components in a Container • By Default Every Container Object has an Associated LayoutManger • Panel Objects - FlowLayout • Window Object - BorderLayout

  34. Layout Managers - Simple • FlowLayout • Default for Panel Objects • Lays out Components from Left to Right Starting New Rows if Needed • GridLayout • Displays the Components in Equal Size in the Requested Number of Rows and Columns

  35. Layout Managers - Special Purpose • BorderLayout • Default for Window Objects • Uses 5 Areas to hold Components: North, South, East, West, and Center • CardLayout • One Area Contains Different Components at Different Times

  36. Layout Managers - Flexible • GridBagLayout • Aligns Components by Placing them in a Grid of Cells • Allows some Components to Span more than one Cell • The Rows and Columns have Different Heights and Widths

  37. Example of a GUI applet TextField Name TextArea Address Label Order Now CheckBox Size Choices Color OK Cancel Quit Button

  38. Excerpts for GUI Applet Example(Note: Many Lines Omitted!!) import java.applet.*; import java.awt.*; import Message; public class Sample extends Applet { Panel p1, p2; Label l1, l2, l3, l4, l5; TextField name; TextArea address; Checkbox order; Choice size, color; Button ok, clear, quit ; Message message;

  39. Excerpts for GUI Applet Example (Note: Many Lines Omitted!!) p1.setLayout(new GridLayout(0,2,2,2)); p1.add(l1); p1.add(name); p1.add(l2); p1.add(address); p1.add(l3); p1.add(order); p1.add(l4); p1.add(size); p1.add(l5); p1.add(color); p2.setLayout(new FlowLayout()); p2.add(ok); p2.add(clear); p2.add(quit); setLayout(new BorderLayout()); add("North", p1); add("South", p2); } public void init() { p1 = new Panel(); p2 = new Panel(); l1 = new Label("Name"); l2 = new Label("Address"); // … other labels omitted name = new TextField(30); address = new TextArea(3, 30); order = new Checkbox(); size = new Choice(); size.addItem("Small"); size.disable(); ok = new Button("OK"); clear = new Button("Clear"); quit = new Button("Quit");

  40. Excerpts for GUI Applet Example (Note: Many Lines Omitted!!) public boolean action(Event e, Object o) { if(e.target == ok) { // You must provide the actions/code } if(e.target == clear) { // You must provide the actions/code } if(e.target == quit) { // You must provide the actions/code } if(e.target == order) { if(order.getState() == true) { // You must provide the actions/code } else if(order.getState() == false) { // You must provide the actions/code } } return true; } }

  41. Event Handling • When a User Acts on a Component, the AWT Detects the Event and Notifies the Event Listeners • A Class Implements the Event Listener and Every Class Instance can Register as Event Listeners • Steps for Implementing and Registering: • Declare that a Class Implements a Listener Interface in the Class declaration • Implement the Listener methods in the Class • Register an Instance of the Class as a Listener on One or More Components

  42. Example of Event Handling public class Beeper ... implements ActionListener { ... // where initialization occurs: button.addActionListener(this); ... public void actionPerformed(ActionEvent e) { // Make a beep sound ... } }

  43. The AWT Events • Action Events • Adjustment Event • Component Events • Container Events • Focus Events • Item Events • Key Events • Mouse Events • Mouse-Motion Events • Text Events • Window Event

  44. Action Listeners • Easiest Event Handlers to Implement • Generated by: • Clicking a Button • Double Clicking a List Item • Choosing a Menu Item • Pressing Return in a Text Field • Listener Interface - ActionListener • Methods - actionPerformed(ActionEvent)

  45. Action Listeners - ActionEvent • Parameter to the actionPerfomed Method • ActionEvent Defines Two Useful Methods • String setActionCommand • Associates a string to the action • String getActionCommand • Returns the string associated with this action

  46. Item Listeners • Generated by Components that Maintain State, Generally on/off State • Components that Generate ItemEvents: • Checkboxes • Choices • Lists • Listener Interface - ItemListener • Methods - itemStateChanged(ItemEvent)

  47. ItemListeners - ItemEvent • Parameter to the itemStateChanged Method • ItemEvent Defines Two Useful Methods: • Object getItem() • Returns the component specific object associated with the item whose state has changed • int getStateChange() • Returns the new state of the item • SELECTED = 1 • DESELECTED = 0

  48. Excerpts for GUI Applet with Listener(Note: Many Lines Omitted!!) import java.applet.*; import java.awt.*; import java.awt.event.*; import Message; public class Sample1 extends Applet implements ActionListener, ItemListener { // Declarations similar to previous example static final String OK = "ok"; public void init() { // Init actions similar to previous example, // except for code shown below for checkbox and buttons order = new Checkbox(); order.addItemListener(this); ok = new Button("OK"); ok.setActionCommand(OK); ok.addActionListener(this); }

  49. Excerpts for GUI Applet with Listener(Note: Many Lines Omitted!!) public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if(command == OK) { // You must provide the actions/code } if(command == CLEAR) { // You must provide the actions/code } if(command == QUIT) { // You must provide the actions/code } } public void itemStateChanged(ItemEvent e1) { if(e1.getStateChange() == ItemEvent.SELECTED) { // You must provide the actions/code } else { // You must provide the actions/code } } }

  50. Designing and Developing Java Classes • Encapsulation Capabilities of Java • Classes (Data + Operations) - ADTs • Packages - Collections of “Related” Classes • Class Declaration: • Access Modes and Variable Members • Constructors and Class Bodies • Method Declaration and Access Modes • Class and Instance Members • Garbage Collection

More Related