You are on page 1of 6

MC0078- Java Programming

Q1 What are the difference between an interface and an abstract class?


Ans 1 The difference between an interface and an abstract class

1. Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior. 2. Variables declared in a Java interface is by default final. An abstract class may contain nonfinal variables. 3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc.. 4. Java interface should be implemented using keyword implements; A Java abstract class should be extended using keyword extends. 5. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces. 6. A Java class can implement multiple interfaces but it can extend only one abstract class. 7. Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists. 8. In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.

Q2 Explain the following with respect to Inheritance in Java: (A) Various Access Specifiers and their usage (B) Abstract classes and their applications
Ans 2 (A) Various Access Specifiers and their usage:One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. In this way the chance of making accidental mistakes in changing values is minimized. Java allows you to control access to classes, methods, and fields via so-called access specifiers. public classes, methods, and fields can be accessed from everywhere. The only constraint is that a file with Java source code can only contain one public class whose name must also match with the filename. If it exists, this public class represents the application or the applet, in which case the public keyword is necessary to enable your Web browser or applet viewer to show the applet. if you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.

private 1

private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So the private access specifier is opposite to the public access specifier. It is mostly used for encapsulation: data are hidden within the class and accessor methods are provided. Ans 2 (B) Abstract classes and their applications:We use Abstract class and interface to enforce some rules to the classes which extends/implements. For example we can define a class say "Bird" and we can declare methods say "Fly()", "Walk()". This means whatever the class that is derived from Bird has to override or give definition for Fly() and Walk() and therefore we are making sure that all the derived classes follows or has the common functionalities. In other way the classes derived from superclass should have common properties. In addition to this the derive class can have its own methods like "Swim()"... In case of Abstract class we can define COMMON functionalities in super class and those can be used in the derived class where as in Interface we cant do that ( this i would say as advantage of abstract class) In case of Interface the derived class can implement any number of interface but restricted to extend only one abstract class (this i would say as advantage of Interface)

Q3 Describe Exception Handling in JAVA


Ans 3 Exception are such anomalous conditions (or typically an event) which changes the normal flow of execution of a program. Exceptions are used for signalling erroneous (exceptional) conditions which occur during the run time processing. Exceptions may occur in any programming language. Occurrence of any kind of exception in java applications may result in an abrupt termination of the JVM or simply the JVM crashes which leaves the user unaware of the causes of such anomalous conditions. However Java provides mechanisms to handle such situations through its superb exception handling mechanism. The Java programming language uses Exception classes to handle such erroneous conditions and exceptional events. Exception Object In java, when any kind of abnormal conditions occurs within a method then the exceptions are thrown in form of Exception Object i.e. the normal program control flow is stopped and an exception object is created to handle that exceptional condition. This object created is called an exception object the process is termed as throwing an exception. The mechanism of handling an exception is called catching an exception or handling an Exception or simply Exception handling. As we have already learned that, what are the exceptions? Point to be remembering here is that exceptions are not errors rather they are some abnormal conditions that aren't necessarily errors. Therefore, the process of detecting the exceptions and responding to them as well is known as Exception handling. Following are the advantages of Exception-handling in Java:

Exception provides the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. One of the significance of this mechanism is that it throws an exception whenever a calling method encounters an error providing that the calling method takes care of that error. 2

With the help of this mechanism the working code and the error-handling code can be disintegrated. It also gives us the scope of organizing and differentiating between different error types using a separate block of codes. This is done with the help of try-catch blocks. Furthermore the errors can be propagated up the method call stack i.e. problems occurring at the lower level in the chain can be handled by the methods higher up the call chain.

Q4 What do you mean by Object Adapter? Explain with an example?


Ans 4 Using CORBA-based services is rather simple and straightforward: After receiving and translating the IDL file into the target language, all that is needed is an object reference. Henceforth, methods on the remote object can be called through the stub object as if they were local. More thought must be spent on the server-side, where servants are to be provided. Even after registering the actual program code with the ORB - for example by passing C++ objects - the programme will usually want to have a certain control over ORB processing, such as when a method may be executed. Missing control on the server side is also a frequent complaint about RPC, where a server is simply expected to run in perpetuity, not having any control over the execution of incoming requests. In order to allow for different possibilities, the handling of actual user code, servants, is decoupled from normal ORB processing by the introduction of object adapters. An object adapter serves as mediator between the ORB and the servant, providing the ORB with a consistent interface for interacting with user code, and being flexible in cooperating with the servant. Different object adapters could then be provided to suit the various server requirements, and an implementation could choose between them and select the most appropriate. Example

When an invocation is made, the client-side ORB is responsible for interpreting the object's profiles, for locating the server in which the object is implemented, and for sending a request to that server. On the server side, the request is received by the ORB, where three steps of dispatching are necessary: 1. The ORB must find the object adapter that the object is implemented in and pass the request on to that object adapter. 2. The object adapter must find the servant that implements the object. 3. If the servant uses a static skeleton, the request is unpacked by the IDL-generated code and the desired method is invoked. But before any of this can happen, the object adapter must first know about the servant. After registering the servant with the object adapter, an implementation must be able to create and export object references that address the servant. So beside merely performing invocations, the object adapter must provide an administrative interface as well

Q5 Describe the following with respect to implementation of Sockets in Java: (A) Reading from and Writing to a Socket (B) Writing the Server Side of a Socket
Ans 5(A) jokes are favoured by children and are usually vehicles for bad puns. They go like this: . Reading from and Writing to a Socket: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."); 4

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(); } } 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: The first statement in this sequence creates a new Socket object and names it echoSocket. Ans 5(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 Server: "Knock knock!" Client: "Who's there?" Server: "Dexter." Client: "Dexter who?" Server: "Dexter halls with boughs of holly." Client: "Groan." The example consists of two independently running Java programs: the client program and the server program. The server program is implemented by two classes: KnockKnockServer andKnockKnockProtocol, 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

Q6

Define RMI. Define the architecture of RMI invocation.

Ans 6 RMI, the definition of a remote service is coded using a Java interface. The implementation of the remote service is coded in a class. Therefore, the key to understanding RMI is to remember that interfaces define behavior and classes define implementation. Remember that a Java interface does not contain executable code. RMI supports two classes that implement the same interface. The first class is the implementation of the behavior, and it runs on the server. The second class acts as a proxy for the remote service and it runs on the client. 5

A client program makes method calls on the proxy object, RMI sends the request to the remote JVM, and forwards it to the implementation. Any return values provided by the implementation are sent back to the proxy and then to the client's program. RMI Architecture Layers: With an understanding of the high-level RMI architecture, take a look under the covers to see its implementation. The RMI implementation is essentially built from three abstraction layers. The first is the Stub and Skeleton layer, which lies just beneath the view of the developer. This layer intercepts method calls made by the client to the interface reference variable and redirects these calls to a remote RMI service. The next layer is the Remote Reference Layer. This layer understands how to interpret and manage references made from clients to the remote service objects.The connection is a one-to-one (unicast) link. In the Java 2 SDK, this layer was enhanced to support the activation of dormant remote service objects via Remote Object Activation. Stub and Skeleton Layer: The stub and skeleton layer of RMI lie just beneath the view of the Java developer. In this layer, RMI uses the Proxy design pattern as described in the book, Design Patterns by Gamma, Helm, Johnson and Vlissides. In the Proxy pattern, an object in one context is represented by another (the proxy) in a separate context. The proxy knows how to forward method calls between the participating objects. The following class diagram illustrates the Proxy pattern. Remote Reference Layer The Remote Reference Layers defines and supports the invocation semantics of the RMI connection. This layer provides a RemoteRef object that represents the link to the remote service implementation object. The stub objects use the invoke() method in RemoteRef to forward the method call. The RemoteRef object understands the invocation semantics for remote services.

You might also like