Master of Computer Application (MCA) – Semester 4  MC0078
Upcoming SlideShare
Loading in...5
×
 

Master of Computer Application (MCA) – Semester 4 MC0078

on

  • 491 views

Master of Computer Application (MCA) – Semester 4 MC0078

Master of Computer Application (MCA) – Semester 4 MC0078

Statistics

Views

Total Views
491
Views on SlideShare
491
Embed Views
0

Actions

Likes
0
Downloads
17
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Master of Computer Application (MCA) – Semester 4  MC0078 Master of Computer Application (MCA) – Semester 4 MC0078 Document Transcript

  • 1MC0078 – Java ProgrammingQuestion 1- What are the difference between an interface and an abstract class?An abstract class is a class that leaves one or more method implementations unspecified bydeclaring one or more methods abstract. An abstract method has no body (i.e., noimplementation). A subclass is required to override the abstract method and provide animplementation. Hence, an abstract class is incomplete and cannot be instantiated, but canbe used as a base class.An interface is a specification, or contract, for a set of methods that a class that implementsthe interface must conform to in terms of the type signature of the methods. The class thatimplements the interface provides an implementation for each method, just as with anabstract method in an abstract class. So, you can think of an interface as an abstract classwith all abstract methods. The interface itself can have either public, package, private orprotected access defined. All methods declared in an interface are implicitly abstract andimplicitly public. It is not necessary, and in fact considered redundant to declare a method inan interface to be abstract. You can define data in an interface, but it is less common to doso. If there are data fields defined in an interface, then they are implicitly defined to be:Public, Static and Final.The main differences are:1 Methods of a Java interface are implicitly abstract and cannot have implementations.A Java abstract class can have instance methods that implement a default behavior.2 Variables declared in a Java interface is by default final. An abstract class maycontain non-final variables.3 Members of a Java interface are public by default. A Java abstract class can havethe usual flavors of class members like private, protected, etc..4 Java interface should be implemented using keyword “implements”; A Java abstractclass should be extended using keyword “extends”.5 An interface can extend another Java interface only; an abstract class can extendanother Java class and implement multiple Java interfaces.6 A Java class can implement multiple interfaces but it can extend only one abstractclass.7 Interface is absolutely abstract and cannot be instantiated; A Java abstract class alsocannot be instantiated, but can be invoked if a main() exists.8 In comparison with java abstract classes, java interfaces are slow as it requires extraindirection.Question 2 - Explain the following with respect to Inheritance in Java:a) Various Access Specifiers and their usagePublic members can be accessed by anybody. Private members can only be accessed bymember functions of the same class. The derived classes cannot access private members.The protected access specifier restricts access to member functions of the same class, orthose of derived classes.Second, when a derived class inherits from a base class, the access specifiers may changedepending on the method of inheritance. There are three different ways for classes to inheritfrom other classes: public, private, and protected.
  • 2class Pub: public Base {}; // inherit from Base publiclyclass Pri: private Base {}; // inherit from Base privatelyclass Pro: protected Base {}; // inherit from Base protectedlyThere are three ways that members can be accessed:● A class can always access its own members regardless of access specifier.● The public accesses the members of a class based on the access specifiers of thatclass.● A derived class accesses inherited members based on the access specifiers of itsimmediate parent. A derived class can always access its own members regardless ofaccess specifier.Public inheritance - When inherit a base class publicly, all members keep their originalaccess specifications. Private members stay private, protected members stay protected, andpublic members stay public.Private inheritance - With private inheritance, all members from the base class are inheritedas private. This means private members stay private, and protected and public membersbecome private. Note that this does not affect that way that the derived class accessesmembers inherited from its parent! It only affects the code trying to access those membersthrough the derived class.Protected inheritance - Protected inheritance is the last method of inheritance. It is almostnever used, except in very particular cases. With protected inheritance, the public andprotected members become protected, and private members stay private. Protectedinheritance is similar to private inheritance. However, classes derived from the derived classstill have access to the public and protected members directly. The public (stuff outside theclass) does not.The way that the access specifiers, inheritance types, and derived classes interact causes alot of confusion. To try and clarify things as much as possible: First, the base class sets it’saccess specifiers. The base class can always access its own members. The accessspecifiers only affect whether outsiders and derived classes can access those members.Second, derived classes have access to base class members based on the accessspecifiers of the immediate parent. The way a derived class accesses inherited members isnot affected by the inheritance method used! Finally, derived classes can change the accesstype of inherited members based on the inheritance method used. This does not affect thederived classes own members, which have their own access specifiers. It only affectswhether outsiders and classes derived from the derived class can access those inheritedmembers.b) Abstract classes and their applicationsAn abstract class is a class that leaves one or more method implementations unspecified bydeclaring one or more methods abstract. An abstract method has no body (i.e., noimplementation). A subclass is required to override the abstract method and provide animplementation. Hence, an abstract class is incomplete and cannot be instantiated, but canbe used as a base class.abstract public class abstract-base-class-name {// abstract class has at least one abstract methodpublic abstract return-type abstract-method-name ( formal-params );}
  • 3public class derived-class-name extends abstract-base-class-name {public return-type abstract-method-name (formal-params) { stmt-list; }... // other method implementations}It would be an error to try to instantiate an object of an abstract type:abstract-class-name obj = new abstract-class-name();That is, operator new is invalid when applied to an abstract class.abstract class Point {private int x, y;public Point(int x, int y) { this.x = x; this.y = y; }public void move(int dx, int dy) { x += dx; y += dy; plot(); }public abstract void plot(); // has no implementation}abstract class ColoredPoint extends Point {private int color;protected public ColoredPoint(int x, int y, int color){super(x, y); this.color = color; }}class SimpleColoredPoint extends ColoredPoint {public SimpleColoredPoint(int x, int y, int color) { super(x,y,color); }public void plot() { ... } // code to plot a SimpleColoredPoint}Since ColoredPoint does not provide an implementation of the plot method, it must bedeclared abstract. The SimpleColoredPoint class does implement the inherited plot method.It would be an error to try to instantiate a Point object or a ColoredPoint object. However,you can declare a Point reference and initialize it with an instance of a subclass object thatimplements the plot method:Point p = new SimpleColoredPoint(a, b, red); p.plot();An abstract class mixes the idea of mutable data in the form of instance variables, non-abstract methods, and abstract methods. An abstract class with only static final instancevariables and all abstract methods is called an interface.Question 3 - Describe Exception Handling in JAVAAn exception is a problem that arises during the execution of a program. An exception canoccur for many different reasons, including the following:1 A user has entered invalid data.2 A file that needs to be opened cannot be found.3 A network connection has been lost in the middle of communications, or the JVM hasrun out of memory.Some of these exceptions are caused by user error, others by programmer error, and othersby physical resources that have failed in some manner.There are three categories of exceptions:
  • 41 Checked exceptions: A checked exception is an exception that is typically a usererror or a problem that cannot be foreseen by the programmer. For example, if a fileis to be opened, but the file cannot be found, an exception occurs. These exceptionscannot simply be ignored at the time of compilation.2 Runtime exceptions: A runtime exception is an exception that occurs that probablycould have been avoided by the programmer. As opposed to checked exceptions,runtime exceptions are ignored at the time of compilation.3 Errors: These are not exceptions at all, but problems that arise beyond the control ofthe user or the programmer. Errors are typically ignored in your code because youcan rarely do anything about an error. For example, if a stack overflow occurs, anerror will arise. They are also ignored at the time of compilation.Exception Hierarchy:All exception classes are subtypes of the java.lang.Exception class. The exception class is asubclass of the Throwable class. Other than the exception class there is another subclasscalled Error which is derived from the Throwable class. Errors are not normally trapped formthe Java programs. These conditions normally happen in case of severe failures, which arenot handled by the java programs. Errors are generated to indicate errors generated by theruntime environment. Example : JVM is out of Memory. Normally programs cannot recoverfrom errors. The Exception class has two main subclasses : IOException class andRuntimeException Class.Catching Exceptions: A method catches an exception using a combination of the try andcatch keywords. A try/catch block is placed around the code that might generate anexception. Code within a try/catch block is referred to as protected code, and the syntax forusing try/catch looks like the following:try{//Protected code}catch(ExceptionName e1){//Catch block}A catch statement involves declaring the type of exception you are trying to catch. If anexception occurs in protected code, the catch block (or blocks) that follow the try is checked.If the type of exception that occurred is listed in a catch block, the exception is passed to thecatch block much as an argument is passed into a method parameter.Common Exceptions: In java it is possible to define two categories of Exceptions and Errors.1 JVM Exceptions: - These are exceptions/errors that are exclusively or logicallythrown by the JVM. Examples : NullPointerException,ArrayIndexOutOfBoundsException, ClassCastException,2 Programmatic exceptions . These exceptions are thrown explicitly by theapplication or the API programmers Examples: IllegalArgumentException,IllegalStateException.Question 4 - What do you mean by Object Adapter? Explain with an example?In a class adapter design, the new adapter class implements the desired interface andsubclasses an existing class. This approach will not always work, notably when the set ofmethods that need to adapt is not specified in an interface.
  • 5In such a case, create an object adapter—an adapter that uses delegation rather thansubclassing. We can create an object adapter by subclassing the class that you need,fulfilling the required methods by relying on an object of an existing class. The NewClassclass is an example of Adapter. An instance of this class is an instance of the RequiredClassclass. In other words, the NewClass class meets the needs of the client. The NewClassclass can adapt the ExistingClass class to meet the client’s needs by using an instance ofExistingClass.Question 5 - 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 Socketa) Reading from and Writing to a SocketThe Socket class in the java.net package is a platform-independent implementation of theclient end of a two-way communication link between a client and a server. The Socket classsits on top of a platform-dependent implementation, hiding the details of any particularsystem from your Java program. By using the java.net Socket class instead of relying onnative code, your Java programs can communicate over the network in a platform-independent fashion.This client program, EchoTest, connects to the standard Echo server (on port 7) via asocket. The client both reads from and writes to the socket. EchoTest sends all text typedinto its standard input to the Echo server by writing the text to the socket. The server echosall input it receives from the client back through the socket to the client. The client programreads and displays the data passed back to it from the server:import java.io.*;import java.net.*;public class EchoTest {public static void main(String[] args) {Socket echoSocket = null;DataOutputStream os = null;DataInputStream is = null;DataInputStream stdIn = new DataInputStream(System.in);try {echoSocket = new Socket("taranis", 7);os = new DataOutputStream(echoSocket.getOutputStream());is = new DataInputStream(echoSocket.getInputStream());
  • 6} catch (UnknownHostException e) {System.err.println("Dont know about host: taranis");} catch (IOException e) {System.err.println("Couldnt get I/O for the connection to: taranis");}if (echoSocket != null && os != null && is != null) {try {String userInput;while ((userInput = stdIn.readLine()) != null) {os.writeBytes(userInput);os.writeByte(n);System.out.println("echo: " + is.readLine());}os.close();is.close();echoSocket.close();} catch (IOException e) {System.err.println("I/O failed on the connection to: taranis");}}}}The first line in this sequence creates a new Socket object and names it echoSocket.echoSocket = new Socket("taranis", 7);os = new DataOutputStream(echoSocket.getOutputStream());is = new DataInputStream(echoSocket.getInputStream());The Socket constructor used here (there are three others) requires the name of the machineand the port number that you want to connect to. The example program uses the hostnametaranis, which is the name of a (hypothetical) machine on our local network. When you typein and run this program on your machine, you should change this to the name of a machineon your network. Make sure that the name you use is the fully qualified IP name of themachine that you want to connect to. The second argument is the port number. Port number7 is the port that the Echo server listens to. The second line in the code snippet above opensan output stream on the socket, and the third line opens an inputstream on the socket.EchoTest merely needs to write to the output stream and read from the input stream tocommunicate through the socket to the server. The rest of the program achieves this. If youare not yet familiar with input and output streams, you may wish to read Input and OutputStreams. The next section of code reads from Echo Tests standard input stream (where theuser can type data) a line at a time. EchoTest immediately writes the input text followed by anewline character to the output stream connected to the socket.String userInput;while ((userInput = stdIn.readLine()) != null) {os.writeBytes(userInput);os.writeByte(n);System.out.println("echo: " + is.readLine());}The last line in the while loop reads a line of information from the input stream connected tothe socket. The readLine() method blocks until the server echos the information back toEchoTest. When readline() returns, EchoTest prints the information to the standard output.This loop continues--EchoTest reads input from the user, sends it to the Echo server, gets aresponse from the server and displays it--until the user types an end-of-input character.
  • 7When the user types an end-of-input character, the while loop terminates and the programcontinues, executing the next three lines of code:os.close();is.close();echoSocket.close();These lines of code fall into the category of housekeeping. A well-behaved program alwayscleans up after itself, and this program is well-behaved. These three lines of code close theinput and output streams connected to the socket, and close the socket connection to theserver. The order here is important--you should close any streams connected to a socketbefore you close the socket itself.This client program is straightforward and simple because the Echo server implements asimple protocol. The client sends text to the server, the server echos it back. When yourclient programs are talking to a more complicated server such as an http server, your clientprogram will also be more complicated. However, the basics are much the same as they arein this program:1 Open a socket.2 Open an input stream and output stream to the socket.3 Read from and write to the stream according to the servers protocol.4 Close streams.5 Close sockets.Only step 3 differs from client to client, depending on the server. The other steps remainlargely the same.b) Writing the Server Side of a SocketServerSocket is a java.net class that provides a system-independent implementation of theserver side of a client/server socket connection. Typically, the ServerSocket class sits on topof a platform-dependent implementation hiding the details of any particular system from yourJava program. Thus, when working with ServerSockets, you should always use thejava.net.ServerSocket class and bypass the underlying system-dependent functions. In thisway, the Java programs will remain system neutral. The constructor for ServerSocket willthrow and exception if for some reason (the port is already in use) it could not listen on thespecified port. If the server successfully connected to its port, then the ServerSocket objectwas successfully created and the server continues to the next step which is to accept aconnection from a client.Socket clientSocket = null;try {clientSocket = serverSocket.accept();} catch (IOException e) {System.out.println("Accept failed: " + 4444 + ", " + e);System.exit(1);}The accept() method blocks (waits) until a client starts up and connects to the same port (inthis case, port 4444) that the server is listening to. When the client requests a connection,the accept() method accepts the connection, if nothing goes wrong, and returns a socket.
  • 8This Socket object is a reference to the socket that the client used to establish theconnection with the port. Now, both the server and the client are communicating to eachother via the Socket and the ServerSocket is out of the picture for now.Question 6 - Define RMI. Define the architecture of RMI invocation.Remote Method Invocation (RMI) technology, first introduced in JDK 1.1, elevates networkprogramming to a higher plane. Although RMI is relatively easy to use, it is a remarkablypowerful technology and exposes the average Java developer to an entirely new paradigm--the world of distributed object computing. The design goal for the RMI architecture was tocreate a Java distributed object model that integrates naturally into the Java programminglanguage and the local object model. RMI architects have succeeded; creating a system thatextends the safety and robustness of the Java architecture to the distributed computingworld.Interfaces: The Heart of RMIThe RMI architecture is based on one important principle: the definition of behavior and theimplementation of that behavior are separate concepts. RMI allows the code that defines thebehavior and the code that implements the behavior to remain separate and to run onseparate JVMs.Specifically, in RMI, the definition of a remote service is coded using a Java interface. Theimplementation of the remote service is coded in a class. Therefore, the key tounderstanding RMI is to remember that interfaces define behavior and classes defineimplementation.RMI supports two classes that implement the same interface. The first classis the implementation of the behavior, and it runs on the server. The second class acts as aproxy for the remote service and it runs on the client.A client program makes method calls on the proxy object, RMI sends the request to theremote JVM, and forwards it to the implementation. Any return values provided by theimplementation are sent back to the proxy and then to the clients program.RMI Architecture Layers - The RMI implementation is essentially built from threeabstraction layers. The first is the Stub and Skeleton layer, which lies just beneath the viewof the developer. This layer intercepts method calls made by the client to the interfacereference variable and redirects these calls to a remote RMI service.The next layer is theRemote Reference Layer. This layer understands how to interpret and manage referencesmade from clients to the remote service objects. The transport layer is based on TCP/IPconnections between machines in a network. It provides basic connectivity, as well as somefirewall penetration strategies.Stub and Skeleton Layer - The stub and skeleton layer of RMI lie just beneath the view ofthe Java developer. In this layer, RMI uses the Proxy design pattern. In the Proxy pattern, anobject in one context is represented by another (the proxy) in a separate context. The proxyknows how to forward method calls between the participating objects.Remote Reference Layer - The Remote Reference Layers defines and supports theinvocation semantics of the RMI connection. This layer provides a RemoteRef object thatrepresents the link to the remote service implementation object.The stub objects use the invoke() method in RemoteRef to forward the method call. TheRemoteRef object understands the invocation semantics for remote services.Transport Layer - The Transport Layer makes the connection between JVMs. Allconnections are stream-based network connections that use TCP/IP.Even if two JVMs arerunning on the same physical computer, they connect through their host computers TCP/IPnetwork protocol stack.