Download document 8363239

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Advanced Programming
Rabie A. Ramadan
[email protected]
Lecture 5
Item 13: Use objects to manage resources.
2
Q1: what might goes wrong with
the following code:
class Investment { … };
Investment *createInvestment();
// factory function, caller must delete
pointer
// when finished using it
void f() {
Investment *pInv = createInvestment();
Looks OK, but what if premature return?
…
OR, exception thrown?
delete pInv;
Even if correct at first, what happens as code is
}
3
maintained?
Q2: how can I solve this problem
?
class Investment { … };
Investment *createInvestment();
// factory function, caller must delete
pointer
// when finished using it
void f() {
Investment *pInv = createInvestment();
…
delete pInv;
}
4
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<Investment> pInv(createInvestment());
… // use pInv as before
}
call to factory function
will delete pInv via auto_ptr’s destructor
Q3: what is the problem with auto
pointers ?
•
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<Investment> pInv1(createInvestment());
std::auto_ptr<Investment> pInv2(pInv1); // pInv1 now
NULL
pInv1 = pInv2; // pInv2 now NULL
6
Q4: what are the other alternatives ?


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<Investment>
pInv1(createInvestment()); // count=1
std::tr1::shared_ptr<Investment> 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.
7
Q5: why it is not recommended to use
these pointers with arrays?


auto_ptr and tr1::shared_ptr use delete, not delete [] in their
destructors
Bad idea:
std::auto_ptr<std::string> aps(new std::string[10]);
std::tr1::shared_ptr<int> spi(new int[1024]);


Boost library has classes for dealing with arrays.
You can also create your own resource-managing
class.
8
Item 14: Think carefully about copying
behavior in resource-managing classes.
9
Q6: what is the main idea behind item
14?

Copying behavior in resource-managing classes

Sometimes you need to use your own recourse
manger class for pointers .

Not all pointers kept in heap
10
Q7: what is the problem you should
handle if you use your own resource
manger class ?

Copying such pointer
11
Q8: what are the possible
solution ?

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.
12
Q8

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.
13
Chapter 10
Applets
14
Q9: What is the main structure
of an Applet’s class ?
15
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... */
}
16
The Applet Class
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.
17
Q10: Draw a flowchart showing how
the browser deals with applets ?
18
Q11: When the init() Method is
called ?
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 userinterface components, and getting string parameter values
from the <applet> tag in the HTML page.
19
Q12: When the start() Method
is called ?
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.
20
Q13: When the stop() Method is
called ?
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.
21
Q14: When the destroy()
Method is called ?
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.
22
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
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
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.
24
Q16: Is there anything wrong
with these two applets ?
25
Q16
Run Applet Viewer
26
Summary

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.
27
Q17: what is the purpose of this
html file?
<applet
code = "DisplayMessage.class"
width = 200
height = 50>
<param name=MESSAGE value="Welcome
to Java">
<param name=X value=20>
<param name=Y value=20>
alt="You must have a Java-enabled
browser to view the applet"
</applet>
28
The <applet> HTML Tag
<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]
>
<param name=param_name1 value=param_value1>
</applet>
29
Q18: What are the similarities between
Applets and Applications ?

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.
30
Q19: What are the differences between
Applets and Applications ?

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.
31
Q20: What are the Security
Restrictions on Applets?

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.
32
Q21:
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
33
Q22: What is wrong with this
code ?
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);
34
Q23: How to run an audio clip in
an applet ?
Class class = this.getClass();
URL url = class.getResource("beep.au");
AudioClip audioClip = Applet.newAudioClip(url);
35
Q24: What is JAR?

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
36
Q25: Why should I use JAR ?
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.
37
Creating JAR
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.
38
Q26 : What is the function of
Manifest File
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
39
Jar and Applete
To run TicTacToe as an applet, modify the <APPLET> 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
>
</APPLET>
40
Q27: Are we satisfying the
following items :

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.
41