Vous êtes sur la page 1sur 17

1MC0078- Java Programming

Assignment set-1

1. What are the difference between an interface and an abstract class?

1. Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code. 2. An class can implement any number of interfaces, but subclass at most one abstract class. 3. An abstract class can have non abstract methods. All methods of an interface are abstract. 4. An abstract class can have instance variables. An interface cannot .5. An abstract class can define constructor. An interface cannot. 6. An abstract class can have any visibility: public, protected, private or none (package). An interface's visibility must be public or none (package). 7. An abstract class inherits from Object and includes methods such as clone() and equals(). 2. Explain the following with respect to Inheritance in Java: a. Various Access Specifiers and their usage An access specifier controls the access of class members and variables by other objects. The various types of access specifiers in Java are:

public private protected friendly or package


The public Access Specifier Class members with public specifier can be accessed anywhere in the same class, package in which the class is created, or a package other than the one in which the class is declared. You can use a public class, data member, or a method from any object in a Java program. The public keyword is used to declare a member as public. The following statement shows how to declare a data member of a class as public: public ; The class Account defines the show () method and various data members, such as name and account number. All the classes in the program can access the various details of a customer, such as name and account number. Therefore, these data members and the method are declared public. The show () method is used to display the account number and customer name of a customer. You can use the following code snippet to define a class, Account that contains public data variables and method: public class Account
Page

2MC0078- Java Programming


{

Assignment set-1

public int account_no; // Data members are accessible outside the class public 'String name; public string name; public void show() //Method declaration { System. out. printIn("Name =" + name); //Statement of the method System.out.printIn("Account number of this customer is= " + account no); } } The private Access Specifier The private access specifier provides most restricted level access. A data member of class declared as private is accessible at the class level only in which it is defined. You can use the private access specifier to declare members that should be available to the class within which they are declared. The private keyword is used to declare a member as private. In Java, you implement the concept of encapsulation by using the private keyword. The following syntax shows how to declare a data member of a class as private: private ; // Private data member of float type private methodName(); // Private method The Account class defines the show() method and the various data members, such as balance and age. These members are to be accessed only by the objects of the same class. Therefore, these methods art declared private. You can use the following code snippet that shows the Account class with private data variables, such as age and balance: class Account { private int account_no; // Data members converted to private to encapsulate private String name; private int age; private float balance; public void show() //Method can be called from outside class to access data //members { System.out.println ("Age of Customer ="+ age); System.out.println("Balance of this customer is=" + balance) ;
Page

3MC0078- Java Programming


} }

Assignment set-1

In the preceding code snippet, the objects of Account class can call the show () method, but objects of other classes cannot access or invoke the private members of Account class. The protected Access Specifier The variables and methods that are declared protected are accessible only to the subclasses of the class in which they are declared. The protected keyword is used to declare a member as protected. The following statement shows how to declare a member as protected:

protected ;
In an airline reservation application, you can create the Ticket class that consists of various data members, such as flightNumber, date, time, and destination. You can derive the ConfirmedTicket subclass from the Ticket class that consists of an additional data member, seatNumber. You can declare the data members of the Ticket class as protected, which can be accessed by the ConfirmedTicfcet subclass. You can use the following code snippet to define the Ticket class that has protected data variables: public class Ticket { protected int flightNumber; //protected data members accessible to derived classes protected String date; protected String time; protected String destination; protected void showData() { //Code Body } } In the preceding code snippet, various data members and methods are declared protected. The friendly or package Access Specifier If you do not specify any access specifier, the scope of data members and methods is friendly. Java provides a large number of classes, which are organized into groups in a package. A class, variable, or method that has friendly access is accessible only to the classes of a package.

Page

4MC0078- Java Programming

Assignment set-1

The data members, such as pageNumbers and price, and the showData() method of the Books class are not given access specifiers. The following code snippet shows the Books class that has friendly access specifier: Class Books { Int pageNumbers; //The default friendly access is provided to the data memners float price; void showdata() { //code body } } In Java, friendly is not a keyword. It is a term that is used for the access level when no access specifier has been specified. You cannot declare a class, variable, or method with the friendly specifier. b. Abstract classes and their applications There are situations in which you will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the subclasses must implement. One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. This is the case with the class Figure used in the preceding example. The definition of area( ) is simply a placeholder. It will not compute and display the area of any type of object.

As you will see as you create your own class libraries, it is not uncommon for a method to have no meaningful definition in the context of its superclass. You can handle this situation two ways. One way, as shown in the previous example, is to simply have it report a warning message. While this approach can be useful in certain situations such as debuggingit is not usually appropriate. You may have methods which must be overridden by the subclass in order for the subclass to have any meaning. Consider the class Triangle. It has no meaning if area( ) is not defined. In this case, you want some way to ensure that a subclass does, indeed, override all necessary methods. Java's solution to this problem is the abstract method. You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the superclass. Thus, a
Page

5MC0078- Java Programming

Assignment set-1

subclass must override themit cannot simply use the version defined in the superclass. To declare an abstract method, use this general form: abstract type name(parameter-list); As you can see, no method body is present. Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined. Also, you cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract. Here is a simple example of a class with an abstract method, followed by a class which implements that method: // A Simple demonstration of abstract. abstract class A { abstract void callme(); // concrete methods are still allowed in abstract classes void callmetoo() { System.out.println("This is a concrete method."); } } class B extends A { void callme() { System.out.println("B's implementation of callme."); } } class AbstractDemo { public static void main(String args[]) { B b = new B(); b.callme(); b.callmetoo(); } } Notice that no objects of class A are declared in the program. As mentioned, it is not possible to instantiate an abstract class. One other point: class A implements a concrete method called callmetoo( ). This is perfectly acceptable. Abstract classes can include as much implementation as they see fit. Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time polymorphism is
Page

6MC0078- Java Programming

Assignment set-1

implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. You will see this feature put to use in the next example. Using an abstract class, you can improve the Figure class shown earlier. Since there is no meaningful concept of area for an undefined two-dimensional figure, the following version of the program declares area( ) as abstract inside Figure. This, of course, means that all classes derived from Figure must override area( ). // Using abstract methods and classes. abstract class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } // area is now an abstract method abstract double area(); } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } class AbstractAreas { public static void main(String args[]) { // Figure f = new Figure(10, 10); // illegal now
Page

7MC0078- Java Programming

Assignment set-1

Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; // this is OK, no object is created figref = r; System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); } } As the comment inside main( ) indicates, it is no longer possible to declare objects of type Figure, since it is now abstract. And, all subclasses of Figure must override area( ). To prove this to yourself, try creating a subclass that does not override area( ). You will receive a compile-time error. Although it is not possible to create an object of type Figure, you can create a reference variable of type Figure. The variable figref is declared as a reference to Figure, which means that it can be used to refer to an object of any class derived from Figure. As explained, it is through superclass reference variables that overridden methods are resolved at run time.
3. Describe Exception Handling in JAVA When an unexpected error occurs in a method, Java creates an object of the appropriate exception class. After creating the exception objects, Java passes it to the program, by an action called throwing an exception. The exception object contains information about the type of error and the state of the program when the exception occurred. You need to handle the exception using exception-handler and process the exception. You can implement exception-handling in your program by using following keywords: try catch finally The try Block You need to guard the statements that may throw an exception in the try block. The following skeletal code illustrates the use of the try block try { // statement that may cause an exception } The try block governs the statements that are enclosed within it and defines the scope of the exception handlers associated with it. In other words, if an exception occurs within try block, the
Page

8MC0078- Java Programming

Assignment set-1

appropriate exception-handler that is associated with the try block handles the exception. A try block must have at least one catch block that follow it immediately. Nested try Statements The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement's catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception. Here is an example that uses nested try statements: // An example of nested try statements. class NestTry { public static void main(String args[ ]) { try { int a = args.length; /* If no command-line args are present, the following statement will generate a divide-by-zero exception. */ int b = 42 / a; System.out.println("a = " + a); try { // nested try block /* If one command-line arg is used, then a divide-by-zero exception will be generated by the following code. */ if(a==1) a = a/(a-a); // division by zero /* If two command-line args are used, then generate an out-of-bounds exception. */ if(a==2) { int c[ ] = { 1 }; c[42] = 99; // generate an out-of-bounds exception } } catch(ArrayIndexOutOfBoundsException e) { } } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } } } As you can see, this program nests one try block within another. The program works as follows. When you execute the program with no command-line arguments, a divide-by zero exception is generated by the outer try block. Execution of the program by one command-line argument generates a divide-by-zero exception from within the nested try block. Since the inner block does not catch this exception, it is passed on to the outer try block, where it is handled. If you

Page

9MC0078- Java Programming

Assignment set-1

execute the program with two command-line arguments, an array boundary exception is generated from within the inner try block. Here are sample runs that illustrate each case: C:\\>java NestTry Divide by 0: java.lang.ArithmeticException: / by zero C:\\>java NestTry One a=1 Divide by 0: java.lang.ArithmeticException: / by zero C:\\>java NestTry One Two a=2 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException: 42 Nesting of try statements can occur in less obvious ways when method calls are involved. For example, you can enclose a call to a method within a try block. Inside that method is another try statement. In this case, the try within the method is still nested inside the outer try block, which calls the method. Here is the previous program recoded so that the nested try block is moved inside the method nesttry( ): /* Try statements can be implicitly nested via calls to methods. */ class MethNestTry { static void nesttry(int a) { try { // nested try block /* If one command-line arg is used, then a divide-by-zero exception will be generated by the following code. */ if(a==1) a = a/(a-a); // division by zero /* If two command-line args are used, then generate an out-of-bounds exception. */ if(a==2) { int c[ ] = { 1 }; c[42] = 99; // generate an out-of-bounds exception } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } public static void main(String args[ ]) { try { int a = args.length; /* If no command-line args are present, the following statement will generate a divide-by-zero exception. */ int b = 42 / a; System.out.println("a = " + a); nesttry(a); } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); }
Page

10MC0078- Java Programming

Assignment set-1

} } The output of this program is identical to that of the preceding example. The catch Block You associate an exception-handler with the try block by providing one or more catch handlers immediately after try block. The following skeletal code illustrates the use of the catch block. try { //statements that may cause an exception } catch () { // error handling code } The catch statement takes an object of an exception class as a parameter. If an exception is thrown, the statements in the catch block are executed. The scope of the catch block is restricted to the statements in the preceding try block only. The finally Block When an exception is raised, the rest of the statements in the try block are ignored. Sometimes, it is necessary to process certain statements irrespective of whether an exception is raised or not. The finally block is used for this purpose. try { openFile(); writeFile(); //may cause an exception } catch () { //process the exception } In the above example, the file has to be closed irrespective of whether an exception is raised or not. You can place the code to close the file in both the try and catch blocks. To avoid duplication of code, you can place the code in the finally block. The code in the finally block is executed regardless of whether an exception is thrown or not. The finally block follows the catch blocks. You have only one finally block for an exception-handler. However, it is not mandatory to have a finally block. finally { closeFile (); } 4. What do you mean by Object Adapter? Explain with an example? The CORBA specification defines the concept of an object adapter. An object adapter is a framework for implementing CORBA objects. It provides an API that object implementations use for various low level services. According to the CORBA specification, an object adapter is responsible for the following functions:
Page

10

11MC0078- Java Programming


Assignment set-1

Generation and interpretation of object references Method invocation Security of interactions Object and implementation activation and deactivation Mapping object references to the corresponding object implementations Registration of implementations

The architecture supports the definition of many kinds of object adapters. The specification includes the definition of the basic object adapter (BOA). In the previous section, you saw some server code that uses the services of VisiBroker's implementation of the BOA. The BOA has been implemented in various CORBA products. Unfortunately, since the specification of the BOA was not complete, the various BOA implementations differ in some significant ways. This has compromised server portability. To address this shortcoming, an entirely new object adapter was added, the portable object adapter (POA). Unfortunately, the POA is not yet supported in many products. In any event, the BOA and the POA are described here. 1 Activation on Demand by the Basic Object Adapter (BOA) One of the main tasks of the BOA is to support on-demand object activation. When a client issues a request, the BOA determines if the object is currently running and if so, it delivers the request to the object. If the object is not running, the BOA activates the object and then delivers the request. The BOA defines four different models for object activation:
Shared server Multiple active objects share the same server. The server services requests from multiple clients. The server remains active until it is deactivated or exits. Only one object is active in the server. The server exits when the client that caused its activation exits. Each request results in the creation of a server. The server exits when the method completes. The server is started by an entity other than the BOA (you, operating services, etc.). Multiple active objects share the server.

Unshared server Server-per-method Persistent server

5. Describe the following with respect to implementation of Sockets in Java: a. Reading from and Writing to a Socket Let's look at a simple example that illustrates how a program can establish a connection to a server program using the Socket class and then, how the client can send data to and receive data from the server through the socket. The example program implements a client, EchoClient,
Page

11

12MC0078- Java Programming

Assignment set-1

that connects to the Echo server. The Echo server simply receives data from its client and echoes it back. The Echo server is a well-known service that clients can rendezvous with on port 7. EchoClient creates a socket thereby getting a connection to the Echo server. It reads input from the user on the standard input stream, and then forwards that text to the Echo server by writing the text to the socket. The server echoes the input back through the socket to the client. The client program reads and displays the data passed back to it from the server: import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: taranis."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); } } Note that EchoClient both writes to and reads from its socket, thereby sending data to and receiving data from the Echo server.

Page

12

13MC0078- Java Programming

Assignment set-1

Let's walk through the program and investigate the interesting parts. The three statements in the try block of the main method are critical. These lines establish the socket connection between the client and the server and open a PrintWriter and a BufferedReader on the socket: echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); b. Writing the Server Side of a Socket This section shows you how to write a server and the client that goes with it. The server in the client/server pair serves up Knock Knock jokes. Knock Knock jokes are favored by children and are usually vehicles for bad puns. They go like this: Server:"Knockknock!" Client:"Who'sthere?" Server:"Dexter." Client:"Dexterwho?" Server:"Dexterhallswithboughsofholly." Client: "Groan." The example consists of two independently running Java programs: the client program and the server program. The client program is implemented by a single class, KnockKnockClient, and is very similar to the EchoClient example from the previous section. The server program is implemented by two classes: KnockKnockServer and KnockKnockProtocol, KnockKnockServer contains the main method for the server program and performs the work of listening to the port, establishing connections, and reading from and writing to the socket. KnockKnockProtocol serves up the jokes. It keeps track of the current joke, the current state (sent knock knock, sent clue, and so on), and returns the various text pieces of the joke depending on the current state. This object implements the protocol-the language that the client and server have agreed to use to communicate. The following section looks in detail at each class in both the client and the server and then shows you how to run them. The Knock Knock Server This section walks through the code that implements the Knock Knock server program. Here is the complete source for the KnockKnockServer class. The server program begins by creating a new ServerSocket object to listen on a specific port (see the statement in bold in the following code segment). When writing a server, choose a port that is not already dedicated to some other service. KnockKnockServer listens on port 4444 because 4 happens to be my favorite number and port 4444 is not being used for anything else in my environment: try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.out.println("Could not listen on port: 4444");
Page

13

14MC0078- Java Programming

Assignment set-1

System.exit(-1); } ServerSocket is a java.net class that provides a system-independent implementation of the server side of a client/server socket connection. The constructor for ServerSocket throws an exception if it can't listen on the specified port (for example, the port is already being used). In this case, the KnockKnockServer has no choice but to exit. If the server successfully binds to its port, then the ServerSocket object is successfully created and the server continues to the next step--accepting a connection from a client (shown in bold): Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.out.println("Accept failed: 4444"); System.exit(-1); } The accept method waits until a client starts up and requests a connection on the host and port of this server (in this example, the server is running on the hypothetical machine taranis on port 4444). When a connection is requested and successfully established, the accept method returns a new Socket object which is bound to the same local port and has it's remote address and remote port set to that of the client. The server can communicate with the client over this new Socket and continue to listen for client connection requests on the original ServerSocket This particular version of the program doesn't listen for more client connection requests. However, a modified version of the program is provided in Supporting Multiple Clients. After the server successfully establishes a connection with a client, it communicates with the client using this code: PrintWriter out = new PrintWriter( clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader( clientSocket.getInputStream())); String inputLine, outputLine; // initiate conversation with client KnockKnockProtocol kkp = new KnockKnockProtocol(); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if outputLine.equals("Bye.")) break; } This code: 1. Gets the socket's input and output stream and opens readers and writers on them. 2. Initiates communication with the client by writing to the socket (shown in bold). 3. Communicates with the client by reading from and writing to the socket (the while loop).
Page

14

15MC0078- Java Programming

Assignment set-1

Step 1 is already familiar. Step 2 is shown in bold and is worth a few comments. The bold statements in the code segment above initiate the conversation with the client. The code creates a KnockKnockProtocol object-the object that keeps track of the current joke, the current state within the joke, and so on. After the KnockKnockProtocol is created, the code calls KnockKnockProtocol's processInput method to get the first message that the server sends to the client. For this example, the first thing that the server says is "Knock! Knock!" Next, the server writes the information to the PrintWriter connected to the client socket, thereby sending the message to the client. Step 3 is encoded in the while loop. As long as the client and server still have something to say to each other, the server reads from and writes to the socket, sending messages back and forth between the client and the server. The server initiated the conversation with a "Knock! Knock!" so afterwards the server must wait for the client to say "Who's there?" As a result, the while loop iterates on a read from the input stream. The readLine method waits until the client responds by writing something to its output stream (the server's input stream). When the client responds, the server passes the client's response to the KnockKnockProtocol object and asks the KnockKnockProtocol object for a suitable reply. The server immediately sends the reply to the client via the output stream connected to the socket, using a call to println. If the server's response generated from the KnockKnockServer object is "Bye." this indicates that the client doesn't want any more jokes and the loop quits. The KnockKnockServer class is a well-behaved server, so the last several lines of this section of KnockKnockServer clean up by closing all of the input and output streams, the client socket, and the server socket: out.close(); in.close(); clientSocket.close(); serverSocket.close(); The Knock Knock Protocol 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. The Knock Knock Client The KnockKnockClient class implements the client program that speaks to the KnockKnockServer. KnockKnockClient is based on the EchoClient program in the previous section, Reading from and Writing to a Socket and should be somewhat familiar to you. But we'll go over the program anyway and look at what's happening in the client in the context of what's going on in the server.
Page

15

16MC0078- Java Programming

Assignment set-1

6. Define RMI. Define the architecture of RMI invocation. RMI applications often comprise two separate programs, a server and a client. A typical server program creates some remote objects, makes references to these objects accessible, and waits for clients to invoke methods on these objects. A typical client program obtains a remote reference to one or more remote objects on a server and then invokes methods on them. RMI provides the mechanism by which the server and the client communicate and pass information back and forth. Such an application is sometimes referred to as a distributed object application. Distributed object applications need to do the following: Locate remote objects: Applications can use various mechanisms to obtain references to remote objects. For example, an application can register its remote objects with RMI's simple naming facility, the RMI registry. Alternatively, an application can pass and return remote object references as part of other remote invocations. Communicate with remote objects: Details of communication between remote objects are handled by RMI. To the programmer, remote communication looks similar to regular Java method invocations. Load class definitions for objects that are passed around: Because RMI enables objects to be passed back and forth, it provides mechanisms for loading an object's class definitions as well as for transmitting an object's data. The following illustration depicts an RMI distributed application that uses the RMI registry to obtain a reference to a remote object. The server calls the registry to associate (or bind) a name with a remote object. The client looks up the remote object by its name in the server's registry and then invokes a method on it. The illustration also shows that the RMI system uses an existing web server to load class definitions, from server to client and from client to server, for objects when needed.

Advantages of Dynamic Code Loading One of the central and unique features of RMI is its ability to download the definition of an object's class if the class is not defined in the receiver's Java virtual machine. All of the types and behavior of an object, previously available only in a single Java virtual machine, can be 16

Page

17MC0078- Java Programming

Assignment set-1

transmitted to another, possibly remote, Java virtual machine. RMI passes objects by their actual classes, so the behavior of the objects is not changed when they are sent to another Java virtual machine. This capability enables new types and behaviors to be introduced into a remote Java virtual machine, thus dynamically extending the behavior of an application. The compute engine example in this trail uses this capability to introduce new behavior to a distributed program. Remote Interfaces, Objects, and Methods Like any other Java application, a distributed application built by using Java RMI is made up of interfaces and classes. The interfaces declare methods. The classes implement the methods declared in the interfaces and, perhaps, declare additional methods as well. In a distributed application, some implementations might reside in some Java virtual machines but not others. Objects with methods that can be invoked across Java virtual machines are called remote objects. An object becomes remote by implementing a remote interface, which has the following characteristics: A remote interface extends the interface java.rmi.Remote. Each method of the interface declares java.rmi.RemoteException in its throws clause, in addition to any application-specific exceptions. RMI treats a remote object differently from a non-remote object when the object is passed from one Java virtual machine to another Java virtual machine. Rather than making a copy of the implementation object in the receiving Java virtual machine, RMI passes a remote stub for a remote object. The stub acts as the local representative, or proxy, for the remote object and basically is, to the client, the remote reference. The client invokes a method on the local stub, which is responsible for carrying out the method invocation on the remote object. A stub for a remote object implements the same set of remote interfaces that the remote object implements. This property enables a stub to be cast to any of the interfaces that the remote object implements. However, only those methods defined in a remote interface are available to be called from the receiving Java virtual machine.

Page

17

Vous aimerez peut-être aussi