Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Answer:
The Applet tag is used to embed an applet in an HTML document the Applet tag takes
zero or more parameters.
Syntax
<APPLET
VSPACE = “vertical space between the applet and the rest of the HTML “
HSPACE = “horizontal space between the applet and the rest of the HTML “
ALIGN = “alignment of the applet with respect to the rest of the web page “
ALT = “alternate text to be displayed if the browser does not support applets “
>
……..
</APPLET>
The most commonly used attributes of the Applet tag are CODE, HEIGHT, WIDTH,
CODEBASE and ALT. You can send parameters to the applet using the PARAM tag.
The PARAM tag must be written between <APPLET> and </APPLET>
Example
<Applet
MI0032 1
Java and Web Design
Height = 200
</applet>
You can describe the life cycle of an applet through four methods. These methods are:
The init () method is called the first time an applet is loaded into the memory of a
computer. You can initialize variables, and add components like buttons and check
boxes to the applet in the init () method.
The start () method is called immediately after the init () method and every time the
applet receives focus as a result of scrolling in the active window. You can use this
method when you want to restart a process, such as thread animation, every time the
applet receives the focus.
The stop () method is called every time the applet loses the focus. You can use this
method to reset variables and stop the threads that are running.
The destroy ( ) method is called by the browser when the user moves to another page.
You can use this method to perform clean-up operations like closing a file.
MI0032 2
Java and Web Design
It is not mandatory to use any or all the methods of the applet. These methods are called
automatically by the Java environment, and hence, must be declared public. None of the
methods accept parameters. For example,
All but the most trivial applets override a set of methods that provides the basic
mechanism by which the browser or applet viewer interfaces to the applet and controls
its execution. Four of these methods–init( ), start( ), stop( ), and destroy( ) – are
defined by Applet. Another, paint( ), is defined by the AWT Component class. Default
implementations for all of these methods are provided. Applets do not need to override
those methods they do not use. However, only very simple applets will not need to
define all of them. These five methods can be assembled into the skeleton shown here:
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/*
</applet>
*/
// Called first.
// initialization
MI0032 3
Java and Web Design
// suspends execution
method executed. */
b. Datagram
Answer: A
The KnockKnockProtocol class implements the protocol that the client and server use to
communicate. This class keeps track of where the client and the server are in their
conversation and serves up the server's response to the client's statements. The
KnockKnockServer object contains the text of all the jokes and makes sure that the
client gives the proper response to the server's statements. It wouldn't do to have the
client say "Dexter who?" when the server says "Knock! Knock!"
All client/server pairs must have some protocol by which they speak to each other;
otherwise, the data that passes back and forth would be meaningless. The protocol that
your own clients and servers use depends entirely on the communication required by
them to accomplish the task.
Answer: B
Clients and servers that communicate via a reliable channel, such as a TCP socket, have
a dedicated point-to-point channel between themselves, or at least the illusion of one. To
communicate, they establish a connection, transmit the data, and then close the
MI0032 4
Java and Web Design
connection. All data sent over the channel is received in the same order in which it was
sent. This is guaranteed by the channel.
In contrast, applications that communicate via datagrams send and receive completely
independent packets of information. These clients and servers do not have and do not
need a dedicated point-to-point channel. The delivery of datagrams to their destinations
is not guaranteed. Nor is the order of their arrival.
The java.net package contains three classes to help you write Java programs that use
datagrams to send and receive packets over the network: DatagramSocket,
DatagramPacket, and MulticastSocketAn application can send and receive
DatagramPackets through a DatagramSocket. In addition, DatagramPackets can be
broadcast to multiple recipients all listening to a MulticastSocket.
The example featured in this section consists of two applications: a client and a server.
The server continuously receives datagram packets over a datagram socket. Each
datagram packet received by the server indicates a client request for a quotation. When
the server receives a datagram, it replies by sending a datagram packet that contains a
one-line "quote of the moment" back to the client.
The client application in this example is fairly simple. It sends a single datagram packet
to the server indicating that the client would like to receive a quote of the moment. The
client then waits for the server to send a datagram packet in response.
Let’s investigate these classes, starting with the class that contains the main method for
the server application. Working with a Server-Side Application contains an applet
version of the QuoteClient class.
The QuoteServer class, shown here in its entirety, contains a single method: the main
method for the quote server application. The main method simply creates a new
QuoteServerThread object and starts it:
import java.io.*;
public class QuoteServer {
public static void main(String[] args) throws IOException {
new QuoteServerThread().start();
}
}
The QuoteServerThread class implements the main logic of the quote server.
MI0032 5
Java and Web Design
try {
in = new BufferedReader(
new FileReader("one-liners.txt"));
} catch (FileNotFoundException e)
System.err.println("Couldn't open quote file. " +
"Serving time instead.");
}
}
Remember that certain ports are dedicated to well-known services and you cannot use
them. If you specify a port that is in use, the creation of the DatagramSocket will fail.
Now for the interesting part of the QuoteServerThread: its run method. The run method
overrides run in the Thread class and provides the implementation for the thread. For
information about threads, see Defining and Starting a Thread.
The run method contains a while loop that continues as long as there are more quotes in
the file. During each iteration of the loop, the thread waits for a DatagramPacket to
arrive over the DatagramSocket. The packet indicates a request from a client. In
response to the client’s request, the QuoteServerThread gets a quote from the file, puts it
in a DatagramPacket and sends it over the DatagramSocket to the client that asked for it.
Let’s look first at the section that receives the requests from clients:
The first statement creates an array of bytes which is then used to create a
DatagramPacket. The DatagramPacket will be used to receive a datagram from the
socket because of the constructor used to create it. This constructor requires only two
arguments: a byte array that contains client-specific data and the length of the byte
array. When constructing a DatagramPacket to send over the DatagramSocket, you also
must supply the Internet address and port number of the packet’s destination. You’ll see
this later when we discuss how the server responds to a client request.
MI0032 6
Java and Web Design
The last statement in the previous code snippet receives a datagram from the socket (the
information received from the client gets copied into the packet). The receive method
waits forever until a packet is received. If no packet is received, the server makes no
further progress and just waits.
Now assume that, the server has received a request from a client for a quote. Now the
server must respond. This section of code in the run method constructs the response:
If the quote file did not get opened for some reason, then in equals null. If this is the
case, the quote server serves up the time of day instead. Otherwise, the quote server gets
the next quote from the already opened file. Finally, the code converts the string to an
array of bytes.
Now, the run method sends the response to the client over the DatagramSocket with this
code:
The first two statements in this code segment get the Internet address and the port
number, respectively, from the datagram packet received from the client. The Internet
address and port number indicate where the datagram packet came from. This is where
the server must send its response. In this example, the byte array of the datagram packet
contains no relevant information. The arrival of the packet itself indicates a request from
a client that can be found at the Internet address and port number indicated in the
datagram packet.
The third statement creates a new DatagramPacket object intended for sending a
datagram message over the datagram socket. You can tell that the new DatagramPacket
is intended to send data over the socket because of the constructor used to create it. This
constructor requires four arguments. The first two arguments are the same required by
the constructor used to create receiving datagrams: a byte array containing the message
from the sender to the receiver and the length of this array. The next two arguments are
different: an Internet address and a port number. These two arguments are the complete
address of the destination of the datagram packet and must be supplied by the sender of
the datagram. The last line of code sends the DatagramPacket on its way.
When the server has read all the quotes from the quote file, the while loop terminates
and the run method cleans up:
socket.close();
MI0032 7
Java and Web Design
The QuoteClient class implements a client application for the QuoteServer. This
application sends a request to the QuoteServer, waits for the response, and, when the
response is received, displays it to the standard output. Let’s look at the code in detail.
The QuoteClient class contains one method, the main method for the client application.
The top of the main method declares several local variables for its use:
int port;
InetAddress address;
DatagramSocket socket = null;
DatagramPacket packet;
byte[] sendBuf = new byte[256];
First, the main method processes the command-line arguments used to invoke the
QuoteClient application:
if (args.length != 1) {
System.out.println("Usage: java QuoteClient <hostname>");
return;
}
The QuoteClient application requires one command-line arguments: the name of the
machine on which the QuoteServer is running.
The client uses a constructor that does not require a port number. This constructor just
binds the DatagramSocket to any available local port. It doesn’t matter what port the
client is bound to because the DatagramPackets contain the addressing information. The
server gets the port number from the DatagramPackets and send its response to that port.
The code segment gets the Internet address for the host named on the command line
(presumably the name of the machine on which the server is running). This InetAddress
and the port number 4445 (the port number that the server used to create its
DatagramSocket) are then used to create DatagramPacket destined for that Internet
address and port number. Therefore the DatagramPacket will be delivered to the quote
server.
Note that the code creates a DatagramPacket with an empty byte array. The byte array is
empty because this datagram packet is simply a request to the server for information.
MI0032 8
Java and Web Design
All the server needs to know to send a response–the address and port number to which
reply–is automatically part of the packet.
Next, the client gets a response from the server and displays it:
To get a response from the server, the client creates a "receive" packet and uses the
DatagramSocket receive method to receive the reply from the server. The receive
method waits until a datagram packet destined for the client comes through the socket.
Note that if the server’s reply is somehow lost, the client will wait forever because of
the no-guarantee policy of the datagram model. Normally, a client sets a timer so that it
doesn’t wait forever for a reply; if no reply arrives, the timer goes off and the client
retransmits.
When the client receives a reply from the server, the client uses the getData method to
retrieve that data from the packet. The client then converts the data to a string and
displays it.
After you’ve successfully compiled the server and the client programs, you run them.
You have to run the server program first. Just use the Java interpreter and specify the
QuoteServer class name.
Once the server has started, you can run the client program. Remember to run the client
program with one command-line argument: the name of the host on which the
QuoteServer is running.
After the client sends a request and receives a response from the server, you should see
output similar to this:
Q.3 What are the different access specifiers in Java? How can we call a superclass
constructor? Explain with a suitable example.
Answer:
An access specifier determines which features of a class (the class itself, the data
members, and the methods) may be used by other classes. Java supports three access
specifiers.
• public.
• private.
• protected.
MI0032 9
Java and Web Design
All classes except inner class (class within classes) can have the public access specifier.
You can use a public class, a data member, or a method from any object in any Java
program.
Example
Only objects of the same class can access a private variable or method. You can declare
only variables, methods, and inner classes as private.
Example
The variables, methods, and inner classes that are declared protected are accessible to
the subclasses of the class in which they are declared.
Example
Default Access
If you do not specify any of the above access specifiers, the scope is friendly. A class,
variable, or method that has friendly access is accessible to all the classes of a package.
Consider the following set of classes. Class Y and Z inherit from class X. Class Z
belongs to a package different than that of classes X and Y
MI0032 10
Java and Web Design
A method accessMe () has been declared in class X. The following table shows you the
accessibility of the method accessMe () from classes Y and Z
You can access a non-private variable or method using an object of the class as shown
below:
classobject.publicvariable;
classobject.protectedmethod ();
Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private. For example, consider
the following simple class hierarchy:
compile.
*/
// Create a superclass.
class A {
MI0032 11
Java and Web Design
i = x;
j = y;
class B extends A {
int total;
void sum() {
class Access {
subOb.setij(10, 12);
subOb.sum();
This program will not compile because the reference to j inside the sum( ) method of B
causes an access violation. Since j is declared as private, it is only accessible by other
members of its own class. Subclasses have no access to it.
Note: A class member that has been declared as private will remain private to its class.
It is not accessibl e by any code outside its class, including subclasses.
MI0032 12
Java and Web Design
double vol;
vol = weightbox.volume();
weightbox.weight);
System.out.println();
plainbox = weightbox;
plainbox.weight);
It is important to understand that it is the type of the reference variable – not the type of
the object that it refers to – that determines what members can be accessed. That is,
MI0032 13
Java and Web Design
Although the preceding may seem a bit esoteric, it has some important practical
applications – two of which are discussed later in this chapter.
Using super
In the preceding examples, classes derived from Box were not implemented as
efficiently or as robustly as they could have been. For example, the constructor for
BoxWeight explicitly initializes the width, height, and depth fields of Box( ). Not only
does this duplicate code found in its superclass, which is inefficient, but it implies that a
subclass must be granted access to these members. However, there will be times when
you will want to create a superclass that keeps the details of its implementation to itself
(that is, that keeps its data members private). In this case, there would be no way for a
subclass to directly access or initialize these variables on its own. Since encapsulation is
a primary attribute of OOP, it is not surprising that Java provides a solution to this
problem. Whenever a subclass needs to refer to its immediate superclass, it can do so by
use of the keyword super.
super has two general forms. The first calls the superclass’ constructor. The second is
used to access a member of the superclass that has been hidden by a member of a
subclass. Each use is examined here.
A subclass can call a constructor method defined by its superclass by use of the
following form of super:
super(parameter-list);
MI0032 14
Java and Web Design
weight = m;
Here, BoxWeight( ) calls super( ) with the parameters w, h, and d. This causes the
Box( ) constructor to be called, which initializes width, height, and depth using these
values. BoxWeight no longer initializes these values itself. It only needs to initialize the
value unique to it: weight. This leaves Box free to make these values private if desired.
In the preceding example, super( ) was called with three arguments. Since constructors
can be overloaded, super( ) can be called using any form defined by the superclass. The
constructor executed will be the one that matches the arguments. For example, here is a
complete implementation of BoxWeight that provides constructors for the various ways
that a box can be constructed. In each case, super( ) is called using the appropriate
arguments. Notice that width, height, and depth have been made private within Box.
class Box {
width = ob.width;
height = ob.height;
depth = ob.depth;
width = w;
height = h;
MI0032 15
Java and Web Design
depth = d;
Box() {
Box(double len) {
double volume() {
super(ob);
weight = ob.weight;
MI0032 16
Java and Web Design
weight = m;
// default constructor
BoxWeight() {
super();
weight = -1;
super(len);
weight = m;
class DemoSuper {
double vol;
vol = mybox1.volume();
MI0032 17
Java and Web Design
System.out.println();
vol = mybox2.volume();
System.out.println();
vol = mybox3.volume();
System.out.println();
vol = myclone.volume();
System.out.println();
vol = mycube.volume();
System.out.println();
MI0032 18
Java and Web Design
super(ob);
weight = ob.weight;
Notice that super( ) is called with an object of type BoxWeight – not of type Box. This
still invokes the constructor Box(Box ob). As mentioned earlier, a superclass variable
can be used to reference any object derived from that class. Thus, we are able to pass a
BoxWeight object to the Box constructor. Of course, Box only has knowledge of its
own members.
Let’s review the key concepts behind super( ). When a subclass calls super( ), it is
calling the constructor of its immediate superclass. Thus, super( ) always refers to the
superclass immediately above the calling class. This is true even in a multileveled
hierarchy. Also, super( ) must always be the first statement executed inside a subclass
constructor.
The second form of super acts somewhat like this, except that it always refers to the
superclass of the subclass in which it is used. This usage has the following general form:
super.member
This second form of super is most applicable to situations in which member names of a
subclass hide members by the same name in the superclass. Consider this simple class
hierarchy:
MI0032 19
Java and Web Design
class A {
int i;
class B extends A {
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
void show() {
class UseSuper {
subOb.show();
i in superclass: 1
i in subclass: 2
MI0032 20
Java and Web Design
Although the instance variable i in B hides the i in A, super allows access to the i
defined in the superclass. As you will see, super can also be used to call methods that
are hidden by a subclass.
An abstract class defines common properties and behaviors of other classes. An abstract
class is used as a base class to derive specific classes of the same kind. It defines
properties common to the classes derived from it. The abstract keyword is used to
declare such a class. The classes declared using the abstract keyword cannot be
instantiated.
Syntax
You can also declare abstract methods. Abstract methods have public scope. The code
below declares an abstract method for the class shape.
The abstract method calculateArea (), given above, is inherited by the subclasses of the
shape class. The subclasses Rectangle, Circle and Hexagon implement this method in
different ways.
float radius;
return radius*22/7;
MI0032 21
Java and Web Design
In the above example, the calculateArea () method has been overridden in the circle
class. If the method is not overridden, the class will inherit the abstract method from the
parent class. Any class that has a abstract method is abstract. Hence, you would not be
able to create an object of the circle class. Therefore, it is necessary to override the
calculateArea () method in the circle class.
A class called password authenticates user login. You do not want anybody to change
the functionality of the class by extending it. To prevent inheritance, use the final
modifier.
Example
You will also find final classes in JDK package. For example, the java.lang.String class
has been declared final. This is done for security reasons. It ensure that any method that
refers to the String class gets the actual String class and not a modified one.
MI0032 22