Presentation is loading. Please wait.

Presentation is loading. Please wait.

M874 Java1 M874 Weekend School An Introduction to Java Programming.

Similar presentations


Presentation on theme: "M874 Java1 M874 Weekend School An Introduction to Java Programming."— Presentation transcript:

1 M874 Java1 M874 Weekend School An Introduction to Java Programming

2 M874 Java2 Contents Presentation 1, Objects Presentation 2, Inheritance Presentation 3, Exceptions Presentation 4, Abstraction Presentation 5, Threads Presentation 6, HCI Presentation 7, Packages Presentation 8, Applets Presentation 9, Network facilities

3 M874 Java3 Presentation 1 Aims Describe what an object is Outline how objects communicate Introduce the idea of a class Provide explanations of the vocabulary terms method, argument, class and object

4 M874 Java4 Objects Objects occur in everyday life. Typical objects in an air-traffic control system are planes, radars and slots. An object is associated with data (state) Objects can send messages to each other. One of the first activities in a project that uses Java is identifying objects.

5 M874 Java5 Objects Objects communicate via messages Plane Radar I have moved my position

6 M874 Java6 Objects and Messages The general form of a message destinationObject.selector(arguments) Object message is sent to Name of message Any arguments

7 M874 Java7 Examples of Messages printer.start() queued(newProcess) canvas.drawline(x1,x2,y1,y2) Note that messages can have no arguments

8 M874 Java8 Java Errors 1 Forgetting that there is a destination object. Missing the arguments. If the message has no arguments then omitting the brackets.

9 M874 Java9 Classes The class is the key idea in an OO language. Classes are like biscuit cutters: they can be used to create objects. Classes define the data that makes up an object. They also define the messages sent to an object and the processing that occurs.

10 M874 Java10 Class Skeleton class Example{ definition of state … definition of methods } Note capitalisation Brackets match State can follow methods

11 M874 Java11 An Example of a Class class Simple{ int x; add(int k){ x+=k; } set(int k){ x = k } Class with a single piece of data (instance variable) and two chunks of code known as methods

12 M874 Java12 The main Method This is a method inserted into the only public class in a file. It carries out execution of a program and acts like a driver program. It must be placed in the class:it is a method. It is of the form public static void main.

13 M874 Java13 What Happens Example e; … e.set(8); … e.add(12); Java finds that e is an Example, looks for set and then copies 8 into k which is then copied into x Java finds that e is an Example, looks for add and then copies 12 into k which is then added to x.

14 M874 Java14 Constructors Constructors are special methods which are used to create space for objects. They have a special syntax. They are used in conjunction with the new facility. They can be associated with any number of arguments ranging from zero.

15 M874 Java15 Example of the Use of a Constructor Example e = new Example(); … Example f = new Example(23); What happens when the new facility is used?

16 M874 Java16 How it Works If you declare no constructors then the Java system will initialise all your scalar instance variables to some default, for example an int will be 0.It will also initialise all object instance variables to null This is poor programming so you need to define all your constructors. Roughly same syntax as methods.

17 M874 Java17 Examples of Constructors Example(){ x = 0; } Example(int startValue){ x = startValue; } First constructor is equivalent to default Second constructor initialises instance variable x to argument startValue

18 M874 Java18 What Happens Example(12); Java system looks for a class Example, then looks for a single argument constructor, if it finds it then it carries out the code defined by the constructor

19 M874 Java19 Java Errors 2 Wrong number and type of arguments in method call. Omitting a constructor. Misspelling or lower case/upper case problems.

20 M874 Java20 The Use of this The keyword this has two functions in Java. It is used within constructors to enable maintainable code to be written. It is used in methods to refer to the current instance variables.

21 M874 Java21 this in Constructors class Example{ int u; Example(int val){ u = val; } Example(){ this(0); } Use the constructor defined in this class which has a single int argument

22 M874 Java22 this in Methods class Example{ int k; setValue(int k){ this.k = k; } … } Set the instance variable in this class to the value of the argument of the method

23 M874 Java23 public, private etc. There are a number of visibility modifiers in Java. You will mainly come across public and private. public means everything is allowed access. private means only entities within a class are allowed access.

24 M874 Java24 Compiling Java Classes A file can contain any number of Java classes. However, only one can be public If you have a number of public classes then place them in separate files Good design dictates that instance variables are private and methods are normally public.

25 M874 Java25 Java Errors 3 Forgetting that one class in a file must be public. Forgetting to name the source file the same as the class name.

26 M874 Java26 Methods Just like subroutines. Pass objects as references and scalar types as values. Prefaced with visibility modifiers. A number of return types including scalar, classes and void.

27 M874 Java27 Example public int exCalc(int a, String b){ return someValue; } This is the method exCalc it returns an int value and has two arguments an int and a String

28 M874 Java28 Presentation 2 Aims Describe the rationale behind OO languages. Show how an OO system consist of class hierarchies. Describe the main reuse facility within Java: inheritance. Describe the use of class (static methods).

29 M874 Java29 The Notion of Hierarchy Plane CargoPlaneFighterPlane Passenger Plane B747B757AirbA320

30 M874 Java30 Hierarchy 1 Classes in a computer system can be arranged in a hierarchy. As you go down the hierarchy the classes become more and more specialised: Plane, PassengerPlane, B757. As you go down the hierarchy more and more facilities are added.

31 M874 Java31 Hierarchy 2 For example, in a Personnel system you might have a section of hierarchy: Employee - SalariedEmployee - ComissionPaidSalariedEmployee. In this example more and more methods and instance variables are added as you proceed down the hierarchy. The way that this is achieved is via inheritance.

32 M874 Java32 Inheritance 1 Is the most important concept in OO languages. Implemented mainly by the extends facility. Various rules are used to determine what methods and instance variables are inherited.

33 M874 Java33 Inheritance 2 If a class A inherits from a class B, then the methods and instance variables of A become associated with objects defined by A. For example, if PassengerPlane inherits from Plane then an instance variable describing the size of the plane would be inherited from Plane.

34 M874 Java34 Inheritance in Java class A{ instance variables of A a1, a2, a3 methods of A m1, m2, m3 } class B extends A{ instance variables of B b1, b2 methods of B n1, n2 } Any object described by B will have five instance variables and can respond to the five messages m1, m2, m3, n1, n2

35 M874 Java35 Reuse Inheritance is the way that reuse is implemented in any OO language. You will need to be completely happy with this notion to use such a language. It will crop up time and time again, for example, to create a window in Java you will need to inherit from a built-in class Frame.

36 M874 Java36 The two Uses of Inheritance There are two uses of inheritance in Java. The first use is where functionality is added to an existing class, for example a WeeklyPaidEmployee class might inherit from an Employee class. The second use is where functionality is changed. This is an example of overriding.

37 M874 Java37 Overriding class A{ instance variables methods m1, m2, m3 } class B extends A{ instance variables methods m2,m4,m5 } When an m2 message is sent to a B object the m2 method within c is executed

38 M874 Java38 Superclass and Subclass Superclass Subclass extends this super

39 M874 Java39 Conventions for Naming this refers to this class. super refers to the superclass. both this and super allow you to refer to the instance variables and methods in a class and its immediate super class.

40 M874 Java40 Using super in Constructors You may remember that we can use the keyword this within constructors. In a similar fashion we can use super in constructors. When it is used it calls on the constructor in the superclass.

41 M874 Java41 Example of super class A{ int instVar; A(int b){ instVar = b; } … } class B extends A{ int anotherVar; B(int c, int d){ super(d); anotherVar = c; } … } initialises the instance variable inherited from A with the value d

42 M874 Java42 Static Methods These are methods whose messages are not sent to objects but to classes. A static method is prefaced with the keyword static. You can also have static variables. These are class globals which are not replicated in each object defined by a class. In Java static methods are usually used to implement general purpose functions such as sin, cos and string conversion functions.

43 M874 Java43 Example of Static Methods The static method valueOf found in java.lang public static String valueOf(int v) String val = String.valueOf(23); Places in val the string value of the integer 23 Note the class name

44 M874 Java44 Java Errors 3 Forgetting the class name when calling a static method. Forgetting to use super within a constructor. Initialising instance variables in their definitions rather than in the constructors.

45 M874 Java45 Presentation 3 Aims To describe how Java handles errors. To show how exception objects can be used for monitoring errors. To describe the use of the throws and throw keyword. To describe the use of the try-catch facility.

46 M874 Java46 Errors Errors can occur any time within a Java program A program runs out of memory. An invalid URL is accessed. A user types in a floating point number when an integer is expected. A program which expects a file containing data is connected up to an empty file. An array overflows.

47 M874 Java47 Exceptions Are a way of handling errors which cannot be anticipated such as mistyped data being provided by the user. Based on the idea of an exception object. The keyword throw creates an exception object which indicates that a problem has occurred.

48 M874 Java48 Creating an Exception if(error condition){ throw new IllegalArgumentException(); } If something has gone wrong then create a new exception object and throw it. IllegalArgument- Exception is a build in class in Java.

49 M874 Java49 Handling Exceptions When an exception is created control is passed to error-handling code. This error handling code is introduced by means of the try-catch facility. A number of exceptions can be handled in the same body of code.

50 M874 Java50 Using try-catch try{ // Code which potentially causes two exceptions // IllegalArgumentException and NumberFormat // Exception } catch(IllegalArgumentException i) {Code for processing the IllegalArgumentException} catch(NumberFormatException n) {Code for processing the NumberFormatException}

51 M874 Java51 try-catch When an Exception object has been created in the code enclosed by a try- catch control is transferred to the code corresponding to the exception. The identifier introduced, for example i in the previous slide is assigned to the exception object and the code within the curly brackets executed.

52 M874 Java52 An Example try{ if(!name.equals(“URL”)) throw new IllegalArgumentException(); } catch(IllegalArgumentException i) {System.out.println(“Problems with URL”)} There is no reference to i here.

53 M874 Java53 Referring to Exception Objects try{ if(!name.equals(“URL”)) throw new IllegalArgumentException(); } catch(IllegalArgumentException i) {System.out.println(“Problems with URL”+i)} Will print out details of the exception i

54 M874 Java54 The throws Keyword This keyword is placed within the header of methods. It indicates that an Exception object has been thrown in the code but no try- catch processing has occurred. Any method that calls this method either has to use try-catch or head itself with throws.

55 M874 Java55 Using Throws public String process(int j)throws IllegalArgumentException { // Processing involving j if (j<0) throw new IllegalArgumentException(); // Processing which eventually returns a string }

56 M874 Java56 The Chain of Exception Handling If you have a number of methods which call each other somewhere a method will have to have a try-catch in it. Also, the compiler will carry out a check that if an Exception object is thrown in the code of a method either the method handles the exception by try-catch or advertises the fact that it will be thrown upwards.

57 M874 Java57 Creating your own exceptions You can easily create your own exceptions by inheriting from an existing exception class. class MyException extends IllegalArgumentException{ } Effective renaming

58 M874 Java58 Presentation 4 Aims To introduce the concept of design facilities in Java. To show how abstract classes embody ideas of abstraction. To show how interfaces implement a form of multiple inheritance.

59 M874 Java59 Abstraction Employee CommisionEmployee Contains code for common bits of an employee, for example the name Contains bits necessary for the class, for example, commission rate

60 M874 Java60 Abstract classes Are classes where some of the methods are left blank. If a programmer wishes to create an object from an abstract class then an error will occur. To produce objects classes need to inherit from the abstract class and override blank methods.

61 M874 Java61 Example of Abstract class abstract class Employee{... public abstract int calculatePay(); … } class SalariedEmployee extends Employee{ … public int calculatePay(){ //Programmer has inserted the code here }

62 M874 Java62 Abstract classes If you inherit from an abstract class then you have to provide the code for the absytact methods in the class, otherwise your resulting class will still be abstract. Abstract classes provide a way of saying: if you are going to create an object of a certain class you are going to have to implement certain method(s).

63 M874 Java63 Interfaces Interfaces are similar to abstract classes. The main difference is that all the methods in an interface are blank. Used to implement multiple inheritance. Can deliver constants but not variables.

64 M874 Java64 Multiple inheritance Single inheritanceMultiple inheritance

65 M874 Java65 Problems with Multiple Inheritance Inefficient. Unreliable. Complex naming conventions.

66 M874 Java66 The Solution- Interfaces If a class implements an interface then it must provide code for all the methods in the interface. It provides a form of certification of all the classes that carry out the implements operation. Important uses include implementing threads and also enumerators. Has achieved greater importance due to its use in the Java event model.

67 M874 Java67 Example class A extends B implements C{ } BC A Code here for all the methods in C and some code which could override methods in B

68 M874 Java68 The Enumeration Interface One of the most difficult concepts to understand in Java. Enables the programmer to iterate over the elements of a collection without knowing how the collection is stored. You need to form an iterator with a constructor which supplies code for the Enumeration methods.

69 M874 Java69 Enumeration class Iterator implements Enumeration{ Iterator(arguments){ … } … // Code for methods of Enumeration } Needed to pass collection data across

70 M874 Java70 Enumeration methods Contains two methods. hasMoreElements, returns true if there are more elements to process. nextElement returns a value from an Enumeration and moves to the next object, note that it returns an object defined by Object.

71 M874 Java71 Example of the use of an Enumeration iter = new Iterator(a);.. while(iter.hasMoreElements()){... Object o =iter.nextElement();... } Code for the processing of each element, make sure that the code processes an Object

72 M874 Java72 Presentation 5 Aims To describe the concept of a Thread. To show how Java implements threads via the Runnable interface. To describe some thread methods.

73 M874 Java73 Threads A thread is a chunk of code which can be executed concurrently with other threads. Many Internet/Intrenet applications are inherently threaded. Threads are normally implemented by using implements on the Runnable interface.

74 M874 Java74 Thread Code class MyThread implements Runnable{ //Any instance variables … public void run(){ //Code for thread } This is the code for the thread new thread objects will be created by new

75 M874 Java75 Manipulating threads Threads are created by the new keyword. This does not start them the method start does this. There are a wide variety of methods to manipulate threads, for example to kill threads and suspend them. Threads continue executing until they finish their run code, sometimes for ever. The thread class has a constructor of type Runnable, this uses an object which implements the Runnable interface.

76 M874 Java76 More thread code class LpThreader implements Runnable{ int value; LpThreader(int limit){ // code for constructor sets value } … public void run(){ // Code for thread possibly accessing value // which is local to the thread }... } Remember to start a thread use start after it has been created

77 M874 Java77 Thread Methods start, starts a created thread executing. stop, stops a thread from running. suspend, temporarily stops a thread from executing. resume, starts a suspended thread up again. setPriority, sets the priority of a thread.

78 M874 Java78 The sleep Method This puts a thread to sleep for a number of milliseconds. It is static. Used when there is no work yet for a thread to do, for example it may be waiting for some data to process. Throws an InterruptedException.

79 M874 Java79 An Example Sleep try{ Thread.sleep(100); } catch InterruptedException e){ // Interrupt code here }; Sleep for 100 ms A thread may try to interrupt a sleeping thread, this is an error so sleep throws an InterruptedException which must be caught

80 M874 Java80 Presentation 6 Aims To describe how windows-based programming is carried out in Java. To show how widgets are laid out. To describe the main Java widgets. To describe how user events are caught and processed.

81 M874 Java81 The Java AWT Implemented as a package. Portable-draws on the underlying widget set of the base OS, for example Motif or System7 widgets. A number of aspects to programming: creation, layout and responding to events.

82 M874 Java82 Components and Containers In Java you have widgets and containers. Widgets are individual elements such as Button and TextArea. Containers hold components, for example Frame.

83 M874 Java83 Containers These are the elements used to contain widgets. Typical Java containers are Frame, Dialog, Panel and Applet. Panel is a notional container used for layout purposes: a Panel can be nested inside a Panel which in turn can be nested in a Panel etc.

84 M874 Java84 Programming the AWT First you need to extend an AWT class like Frame. Next you need to create the components in a constructor. Next you need to set a layout in the constructor. Then you need to add the components to the container.

85 M874 Java85 The final step The final step is to program what should occur when some action such as pressing a button occurs. This is rather picky programming but not too difficult to grasp.

86 M874 Java86 Creating the Components class MyFrame extends Frame{ Button b; TextField t; MyFrame(){ super();... b = new Button(“Press”); t = New TextField(“000”); } … } Note the use of the super constructor to set up the frame

87 M874 Java87 Java Errors 4 Forgetting to create the widget in the constructor. For a container forgetting to use super to create an instance of the container.

88 M874 Java88 Layout The next step is to lay the components out. For this you will need to set some layout pattern on your container. You use the method setLayout for this, but before you use this method you will need to create a layout object. There are a number of layout classes. The course concentrates on the simplest.

89 M874 Java89 Layouts FlowLayout, just flows the components. GridLayout uses a two dimensional grid. BorderLayout uses the points of the compass. CardLayout is used for tabbed dialogues. GridBagLayout is a massively complex layout.

90 M874 Java90 FlowLayout As components are added they are flowed into the container at the next available position. This is the default layout for applets. There is no default layout for any other container, they need to be specified.

91 M874 Java91 Example of FlowLayout MyFrame(){ super(); b = new Button(“Hello”); c = new Button (“Press”); setLayout(new FlowLayout()); add(b); add(c); } Anonymous layout object Means this.add

92 M874 Java92 GridLayout Based on a row and column grid. Constructor requires to int values for rows and column numbers. add works left to right and top to bottom.

93 M874 Java93 GridLayout Example MyFrame(){ super(); b = new Button(“Hello”); t1 = new TextArea(“000”); c = new Button (“Press”); t2 = new TextArea(“000”); setLayout(new GridLayout(2,2)); add(b); add(c); add(t1); add(t2); }

94 M874 Java94 BorderLayout Based on four points of the compass and center. Restricted to five or less elements.

95 M874 Java95 BorderLayout example MyFrame(){ super(); b = new Button(“Hello”); t1 = new TextArea(“000”); c = new Button (“Press”); t2 = new TextArea(“000”); setLayout(new BorderLayout(2,2)); add(“North”, b); add(“South”, c); add(“Center”,t1); add(“West”, t2); } Adds four components note the spelling of Center You can also use constants such as Borderlayout. NORTH

96 M874 Java96 Processing user actions There are various user actions which the AWT is designed to catch. Examples are: button pressed, slider moved, menu clicked, text entered into an text component. A new event model was introduced into Java 1.1 to process events.

97 M874 Java97 The Java event model Requires objects such as applets which need to respond to events to be registered as listeners to the event. These objects must implement listener interfaces. These objects must be registered to listen to events, usually in the constructor.

98 M874 Java98 Event Example import java.awt.*; import java.awt.event.*; public class ButtonExample extends Frame implements ActionListener{ Button b1; public ButtonExample(){ setLayout(new FlowLayout()); b1 = new Button(“Press me”); add(b1); b1.addActionListener(this); pack(); }

99 M874 Java99 Event Example public void actionPerformed(ActionEvent e){ System.out.println(“My button has been pressed”); System.exit(0); } public static void main(String[] args){ ButtonExample bf = new ButtonExample(); bf.setVisible(true); }

100 M874 Java100 Events Although this is a simple example it shows the general form of processing. An object implements a listener interface. An object which implements a listener interface is registered as being a listener of the object causing the event. Code is provided in the methods that have to be implemented to respond to events.

101 M874 Java101 Events There a wide variety of events that can occur, for example events associated with windows or the mouse. However, the general model is the same. One problem is that some interfaces contain a number of methods and you may only need to provide code for a few.

102 M874 Java102 Events One solution is to include blank bodies within the code for these methods. Another solution is to develop an inner class. This is a class which has access to the class in which it is embedded and which extends an adapter class.

103 M874 Java103 Adapter classes An adapter class is a class which corresponds to a listener interface but has blank code supplied for all its methods. The inner class just extends the adapter class and supplies code for any of the methods which are required to respond to events.

104 M874 Java104 Example Class Example{ Example(){.. WindowCloser w = new WindowCloser(); addWindowListener(w);.. } class WindowCloser extends WindowAdapter{ public void windowClosing(WindowEvent w){ System.exit(0); }

105 M874 Java105 The Canvas class Is an invisible container. Used to arrange items on a visible container. Panels can be nested within each other providing a high degree of flexibility.

106 M874 Java106 Example of a Canvas MyFrame(){ // Code here for initialisation and for setting the // layout manager for the frame. p1 = new Panel(); p2 = new Panel(); b1 = new Button(“Press”); b2 = new Button(“Here”); t1 = new TextArea(20); t2 = new TextArea(30); p1.setLayout(new FlowLayout()); p2.setLayout(new GridLayout(1,2)); p1.add(b1); p1.add(t1); p2.add(b2); p2.add(t2); add(p1); add(p2);

107 M874 Java107 Drawing You can draw on any component. Every component provides a method paint which can be overridden to provide drawing. Normally we only draw on objects described by the Canvas class.

108 M874 Java108 Example of drawing MyFrame(){ … c = new Canvas(); … } paint(Graphics g){ // Code her which carries out drawing }

109 M874 Java109 paint paint has a Graphics object as its argument. paint is called automatically when containers are moved, resized etc. In order to program a paint operation you need to call repaint. All drawing is done via sending messages to the Graphics argument.

110 M874 Java110 Presentation 7 Aims To introduce the idea of a package. To introduce the main Java packages. To detail the role of the Object class. To show how the Object class can be used for general purpose data structures.

111 M874 Java111 Packages These provide the libraries which Java uses, Java is a small language and gets its power from the facilities found in the libraries. Packages, apart from java.lang have to be imported. You can import individual classes.

112 M874 Java112 HTML Documentation Documentation for the class libraries is stored using HTML and can be accessed using your favourite browser. The documentation gives the naem of the class all its instance variables and all its methods. You should be totally familiar with ways of accessing this documentation.

113 M874 Java113 Java Errors 5 Forgetting to import a package. When consulting a class description for a method forgetting that it may inherit from a class which contains that method, for example TextArea. Forgetting that a method may be static Treating * as a full wildcard.

114 M874 Java114 import Is used to tell the compiler which classes could be used. import can import the whole of a package or a single class import java.awt.*; import java.awt.Button;

115 M874 Java115 The Main Packages java.lang contains base facilities. java.io contains stream-based facilities. java.net contains network programming facilities. java.util is a general purpose package containing data structure and useful classes such as Date. java.awt contains HCI facilities.

116 M874 Java116 The Object Class One feature of some of the classes in the Java library is the fact that the Object class is used. Object is a class which lies at the top of the object hierarchy. Every class either explicitly or implicity inherits from Object.

117 M874 Java117 Assignments and casting Assignments between objects in a hierarchy are allowed provided they are on an inheritance chain. Two categories of assignment up-casting or down-casting. Up-casting can use normal assignment. Down-casting involves a cast construct.

118 M874 Java118 Examples of Assignments A a = new A(); … B b = new B(); … a = b; … b = a;... Legal Illegal you need to write b = (B) a; We assume that B inherits (extends) A

119 M874 Java119 Rules In an assignment a = b, provided a is a superclass of a then everything will be ok. However b = a requires the bracketed cast. In the first instance the values of instance variables associated with the subclass object are hidden. In the second instance they are made visible.

120 M874 Java120 This holds for objects described by Object Object o; … class A{ … } a = new A(); … o = a; … a = (A) o; Both of these are legal

121 M874 Java121 Why use Object ? In the course there is one important use of Object. It is used as a container for any type of object. Gives a number of difficulties when retrieving or adding an item from a collection.

122 M874 Java122 Example Vector v = new Vector(50); … v.insertElementAt(19,23); … int val = elementAt(19) This should add the int 19 at the 23rd location in the Vector, does it? This should retrieve the element at position 19 and place it in val, does it?

123 M874 Java123 The Answer is No If you look in the HTML documentation for insertElementAt() the first item should be an Object, it is a scalar. If you look in the documentation for elementAt, then the returned object is of class Object, and hence we are trying to assign an object to a scalar.

124 M874 Java124 The Correct Version Vector v = new Vector(50); … v.insertElementAt(new Integer(19),23); … int val = ((Integer)v.elementAt(19)).intValue();

125 M874 Java125 The Writing Part of the Example v.insertElementAt(new Integer(19),23) An object has to be created we use a special class called Integer to do this, such a class is known as an object wrapper

126 M874 Java126 The Reading Part of the Example int val = ((Integer)v.elementAt(19)).intValue(); We need an int This casts the object defined by Object into an Integer object This returns with the int value of the Integer object

127 M874 Java127 Object Wrappers Used to move between objects and scalars in impure object-oriented languages. Java contains a number of object wrappers for its scalars. Each object wrapper contains methods for conversions, warning: they are often static.

128 M874 Java128 Presentation 8 Aims To describe how applets are constructed. To describe the main applet methods. To show how applets interact with a browser.

129 M874 Java129 Applets Snippets of compiled code embedded in a Web page. Applets loaded when browser page is invoked. There are a number of applet life-cycle methods. Developing applets is different to normal development.

130 M874 Java130 Applets and Browsers Browser Server Class file loaded into client security restrictions

131 M874 Java131 Security Restrictions The applet cannot Execute programs on the client. Read a file on the client. Write to the client. Find out system information about the client.

132 M874 Java132 Developing Applets Extend the class Applet. Provide the code. Compile the code. Embed the class file produced by compilation in a Web page via special HTML tags.

133 M874 Java133 Applets and Containers An applet is just like a container. It inherits all the methods associated with containers. It can have a layout manager associated with it although the default is flowLayout.

134 M874 Java134 Applet Code The main difference between an applet and other containers such as Frame is that there is no applet constructor. Initialisation is done in a method init. init is an example of a life-cycle method. Applets are created by inheriting from Applet which contains these methods.

135 M874 Java135 Applet Code class MyApplet extends Applet{ // instance variables public void init(){ //initialisation of variables //construction of Layout objects //initialising files etc. } // other overidden methods }

136 M874 Java136 Other Life-cycle Methods init, called by the Java system when the applet is loaded or reloaded. start, called when the applet has been loaded and can start. stop, called when the user leaves the browser page or exits from the browser.

137 M874 Java137 Java Errors 6 Attempting to execute an applet using java. Writing a constructor for an Applet. Missing out the full signature of a life-cycle method, for example missing public. Trying to embed an applet inside another container such as a frame.

138 M874 Java138 Applets as Containers Applets are containers. Hence other containers such as Panel and Canvas can be embedded in them. Also, components such as buttons and sliders can be placed in them. They inherit all the component methods such as paint, mouseDown.

139 M874 Java139 Tags for Applets <APPLET CODE = MyApplet.class WIDTH = 200 HEIGHT = 300 > This applet will be found in the file MyApplet.class, it will be 200 pixels by 300 and have two parameters

140 M874 Java140 Applet Methods The Applet class is a small one, but it does contain a number of important methods. Contains life-cycle methods. getParameter which gets parameter values. showStatus which displays strings on your browser’s status bar.

141 M874 Java141 Presentation 9 Aims To outline the main net facilities of Java. To describe the URL class. To describe the URLConnection class. To show how connections can be made to remote computers.

142 M874 Java142 The URL class Describes URLs, Universal Resource Locators. Contains a number of constructors to form URLs. Also contains a number of methods which access various components of a URL.

143 M874 Java143 A URL http://www.open.ac.uk/Studentweb/M874/ ProtocolLocationFile

144 M874 Java144 The class URLConnection Establishes a network connection to a given URL. Used to connect across to files on a remote computer. Also enables some information to be extracted from a URL.

145 M874 Java145 Some accessor methods getLastModified() getContentLength() getDate() All return information about the file referenced by the URL

146 M874 Java146 Code example String urGiven = “http://www.open.ac.uk/Base/Data.txt uConnect = new URLConnection(urGiven); InputStream is = uConnect.getInputStream(); DataInputStream di = new DataInputStream(is); We can now read from the file using methods such as readInt.

147 M874 Java147 Applet transfer The previous example described how to connect up to a file which has a URL. If you want to transfer browser control to a URL which references a web page you need to use.

148 M874 Java148 Example AppletContext a = getAppletContext(); URL ur = new URL( http://www.open.ac.uk/Appl5/home.html”); a.showDocument(ur); Note that an appletContext is a data structure used to interface to a browser. The effect of the above is to show the document referenced on the second line in the browser.

149 M874 Java149 Sockets Sockets are used to plug into a remote computer. A number of constructors are associated with a socket. Objects described by Socket can be used to transfer data into and out of a remote computer.

150 M874 Java150 Example String hst = “www.open..ac.uk”; Socket s = new Socket(hst, 37); InputStream is = s.getInputStream(); DataInput Stream ds = new DataInputStream(is); We can now read from the 37 port using the methods found in class DataInputStream Port 37 is the Time port on a computer

151 M874 Java151 ServerSockets These are used to establish connections to clients. Are associated with a port. Use the accept method which waits for a connection. Uses input and output streams.

152 M874 Java152 An example of a simple server written in Java import java.awt.*; import java.net.*; import java.io.*; public class SimplCon { public static void startServer() { ServerSocket ss=null; Socket s = null; PrintStream dos = null; OutputStream os = null; String st; int count = 0, loopCount =1; try{ // Server uses port 1024, clients need to use this port ss= new ServerSocket(1024); }catch(Exception e){System.out.println("Error:Socket not set up");}

153 M874 Java153 Server code while (true){ try{ System.out.println("Waiting for connection "+loopCount); //Server now blocks waiting for a client s = ss.accept(); }catch(Exception e){System.out.println("Error:Problem with connection");} loopCount++; FileInputStream fi=null; try{ os = s.getOutputStream(); dos = new PrintStream(os,true); }catch(Exception e){System.out.println("Error:Problem setting up output stream");} // Server uses the text in file Emails.txt to send to clients // This file must be in the same directory as the server try{ fi =new FileInputStream("Emails.txt"); }catch(FileNotFoundException fnf){System.out.println("Error:File not found");} DataInputStream di = new DataInputStream(fi); try{ st = di.readLine(); while (st!= null){ count++; dos.println(st); st = di.readLine(); }

154 M874 Java154 Server code fi.close(); dos.close(); s.close(); di.close(); }catch(Exception e){System.out.println("Error:Problem with reading");} System.out.println(count+ " lines of text read"); try{ Thread.sleep(3000); }catch(Exception e){}; } static public void main(String args[]) {startServer(); }


Download ppt "M874 Java1 M874 Weekend School An Introduction to Java Programming."

Similar presentations


Ads by Google