Presentation is loading. Please wait.

Presentation is loading. Please wait.

Advanced Programming Rabie A. Ramadan Lecture 5.

Similar presentations


Presentation on theme: "Advanced Programming Rabie A. Ramadan Lecture 5."— Presentation transcript:

1 Advanced Programming Rabie A. Ramadan Rabie@rabieramadan.org Lecture 5

2 Item 13: Use objects to manage resources. 2

3 Q1: what might goes wrong with the following code: 3 class Investment { … }; Investment *createInvestment(); // factory function, caller must delete pointer // when finished using it void f() { Investment *pInv = createInvestment(); … delete pInv; } Looks OK, but what if premature return? OR, exception thrown? Even if correct at first, what happens as code is maintained?

4 Q2: how can I solve this problem ? 4 class Investment { … }; Investment *createInvestment(); // factory function, caller must delete pointer // when finished using it void f() { Investment *pInv = createInvestment(); … delete pInv; }

5 A solution.. Put the resource returned by createInvestment inside an object whose destructor will release the resource when control leaves f. std::auto_ptr is a smart pointer whose destructor automatically calls delete on what it points to void f() { std::auto_ptr pInv(createInvestment()); … // use pInv as before } call to factory function will delete pInv via auto_ptr’s destructor

6 Q3: what is the problem with auto pointers ? 6 There should never be more than one auto_ptr pointing to an object, or the object will be deleted more than once. Copying an auto_ptr sets it to NULL, so copying pointer has sole ownership. std::auto_ptr pInv1(createInvestment()); std::auto_ptr pInv2(pInv1); // pInv1 now NULL pInv1 = pInv2; // pInv2 now NULL

7 Q4: what are the other alternatives ? 7 Sometimes pointers must have “normal” copying behavior (e.g., in container classes) Use reference-counting smart pointer (RCSP). Keeps track of how many objects point to resource, deletes it when nobody points to it. Similar to garbage collection, but can’t break cycles. void f() { std::tr1::shared_ptr pInv1(createInvestment()); // count=1 std::tr1::shared_ptr pInv2(pInv1); // both now point to same object, count = 2 pInv1 = pInv2; // still point to same object, count = 2 } pointers destroyed at end, object count will be 0 so it will be destroyed.

8 Q5: why it is not recommended to use these pointers with arrays? 8 auto_ptr and tr1::shared_ptr use delete, not delete [] in their destructors Bad idea: std::auto_ptr aps(new std::string[10]); std::tr1::shared_ptr spi(new int[1024]); Boost library has classes for dealing with arrays. You can also create your own resource-managing class.

9 Item 14: Think carefully about copying behavior in resource-managing classes. 9

10 Q6: what is the main idea behind item 14? 10 Copying behavior in resource-managing classes Sometimes you need to use your own recourse manger class for pointers. Not all pointers kept in heap

11 Q7: what is the problem you should handle if you use your own resource manger class ? 11 Copying such pointer

12 Q8: what are the possible solution ? 12 Prohibit copying. Might not make sense to have a copy – why would you have a copy of a Lock? Reference-count the underlying resource. Hold the resource until the last object using it has been destroyed. tr1::shared_ptr does this. BUT, shared_ptr deletes resource when reference count is 0, may not be what you want. Can specify “deleter” as second parameter to shared_ptr constructor.

13 Q8 13 Copy the underlying resource. Only purpose of resource-managing class is to ensure resource gets deleted. Makes a deep copy. Transfer ownership of the underlying resource. Used by auto_ptr in Item #13.

14 Chapter 10 Applets 14

15 Q9: What is the main structure of an Applet’s class ? 15

16 16 public class MyApplet extends java.applet.Applet {... /** The no-arg constructor is called by the browser when the Web page containing this applet is initially loaded, or reloaded */ public MyApplet() {... } /** Called by the browser after the applet is loaded */ public void init() {... } /** Called by the browser after the init() method, or every time the Web page is visited */ public void start() {... } /** Called by the browser when the page containing this applet becomes inactive */ public void stop() {... } /** Called by the browser when the Web browser exits */ public void destroy() {... } /** Other methods if necessary... */ }

17 The Applet Class 17 When the applet is loaded, the Web browser creates an instance of the applet by invoking the applet’s no-arg constructor. The browser uses the init, start, stop, and destroy methods to control the applet. By default, these methods do nothing. To perform specific functions, they need to be modified in the user's applet so that the browser can call your code properly.

18 Q10: Draw a flowchart showing how the browser deals with applets ? 18

19 Q11: When the init() Method is called ? 19 Invoked when the applet is first loaded and again if the applet is reloaded. A subclass of Applet should override this method if the subclass has an initialization to perform. The functions usually implemented in this method include creating new threads, loading images, setting up user- interface components, and getting string parameter values from the tag in the HTML page.

20 Q12: When the start() Method is called ? 20 Invoked after the init() method is executed; also called whenever the applet becomes active again after a period of inactivity (for example, when the user returns to the page containing the applet after surfing other Web pages). A subclass of Applet overrides this method if it has any operation that needs to be performed whenever the Web page containing the applet is visited. An applet with animation, for example, might use the start method to resume animation.

21 Q13: When the stop() Method is called ? 21 The opposite of the start() method, which is called when the user moves back to the page containing the applet; the stop() method is invoked when the user moves off the page. A subclass of Applet overrides this method if it has any operation that needs to be performed each time the Web page containing the applet is no longer visible. When the user leaves the page, any threads the applet has started but not completed will continue to run. You should override the stop method to suspend the running threads so that the applet does not take up system resources when it is inactive.

22 Q14: When the destroy() Method is called ? 22 Invoked when the browser exits normally to inform the applet that it is no longer needed and that it should release any resources it has allocated. A subclass of Applet overrides this method if it has any operation that needs to be performed before it is destroyed. Usually, you won't need to override this method unless you wish to release specific resources, such as threads that the applet created.

23 Q15: The Applet class is an AWT class and is not designed to work with Swing components. To use Swing components in Java applets, it is necessary to create a Java applet that extends …………, which is a subclass of …………. 23

24 Q15: 24 The Applet class is an AWT class and is not designed to work with Swing components. To use Swing components in Java applets, it is necessary to create a Java applet that extends javax.swing.JApplet, which is a subclass of java.applet.Applet. JApplet inherits all the methods from the Applet class. In addition, it provides support for laying out Swing components.

25 Q16: Is there anything wrong with these two applets ? 25

26 Q16 26 Run Applet Viewer

27 Summary 27 Always extends the JApplet class, which is a subclass of Applet for Swing components. Override init(), start(), stop(), and destroy() if necessary. By default, these methods are empty. Add your own methods and data if necessary. Applets are always embedded in an HTML page.

28 Q17: what is the purpose of this html file? 28 <applet code = "DisplayMessage.class" width = 200 height = 50> alt="You must have a Java-enabled browser to view the applet"

29 The HTML Tag 29 <applet code=classfilename.class width=applet_viewing_width_in_pixels height=applet_viewing_height_in_pixels [archive= location of archivefile] [codebase=applet_url] [vspace=vertical_margin] [hspace=horizontal_margin] [align=applet_alignment] [alt=alternative_text] >

30 Q18: What are the similarities between Applets and Applications ? 30 Similarities Since JFrame and JApplet both are subclasses of the Container class, all the user interface components, layout managers and event-handling features are the same for both classes.

31 Q19: What are the differences between Applets and Applications ? 31 Differences Applications are invoked from the static main method by the Java interpreter, and applets are run by the Web browser. The Web browser creates an instance of the applet using the applet’s no-arg constructor and controls and executes the applet through the init, start, stop, and destroy methods. Applets have security restrictions Web browser creates graphical environment for applets, GUI applications are placed in a frame.

32 Q20: What are the Security Restrictions on Applets? 32 Applets are not allowed to read from, or write to, the file system of the computer viewing the applets. Applets are not allowed to run any programs on the browser’s computer. Applets are not allowed to establish connections between the user’s computer and another computer except with the server where the applets are stored.

33 Q21: 33 Due to security restrictions, applets cannot access local files. How can an applet load resource files for image and audio? Use URL class instead of absolute location

34 Q22: What is wrong with this code ? 34 ImageIcon imageIcon = new ImageIcon("c:\\book\\image\\us.gif"); jlbl.setIcon(imageIcon); This approach suffers a problem. The file location is fixed since it uses the absolute file path on Window. Thus, the program cannot run on other platforms and cannot run as applet. Example : Class metaObject = this.getClass(); URL url = metaObject.getResource("image/us.gif"); You can now create an ImageIcon using ImageIcon imageIcon = new ImageIcon(url);

35 Q23: How to run an audio clip in an applet ? 35 Class class = this.getClass(); URL url = class.getResource("beep.au"); AudioClip audioClip = Applet.newAudioClip(url);

36 Q24: What is JAR? 36 Java archive file can be used to group all the project files in a compressed file for deployment. The Java archive file format (JAR) is based on the popular ZIP file format. Pack200 tool

37 Q25: Why should I use JAR ? 37 This single file can be deployed on an end-user’s machine as an application. It also can be downloaded to a browser in a single HTTP transaction, rather than opening a new connection for each piece. This greatly simplifies application deployment and improves the speed with which an applet can be loaded onto a web page and begin functioning.

38 Creating JAR 38 jar -cf TicTacToe.jar TicTacToe.class TicTacToe$Cell.class The -c option is for creating a new archive file, The -f option specifies the archive file’s name.

39 Q26 : What is the function of Manifest File 39 The manifest is a special file that contains information about the files packaged in a JAR file. For instance, the manifest file in TicTacToe.jar contains the following information: Manifest-Version: 1.0 Name: TicTacToe.class Java-Bean: True Name: TioTacToe$Cell.class Java-Bean: True

40 Jar and Applete 40 To run TicTacToe as an applet, modify the tag in the HTML file to include an ARCHIVE attribute. The ARCHIVE attribute specifies the archive file in which the applet is contained. For example, the HTML file for running TicTacToe can be modified as shown below: <APPLET CODE = "TicTacToe.class" ARCHIVE = "TicTacToe.jar" WIDTH = 400 HEIGHT = 300 HSPACE = 0 VSPACE = 0 ALIGN = Middle >

41 Q27: Are we satisfying the following items : 41 Acquire the basic knowledge and essential concepts of Java programming including data types, loops, arrays, classes, inner and outer classes, the concept of Servlets, and Applets programming. Acquire advanced knowledge in C++ programming through learning different advanced skills.


Download ppt "Advanced Programming Rabie A. Ramadan Lecture 5."

Similar presentations


Ads by Google