Академический Документы
Профессиональный Документы
Культура Документы
Java solution
2008
Here, b2 is a reference to ColorBox objects, and b1 is a reference to Box objects. Since ColorBox is a
subclass of Box, it is permissible to assign b1 a reference to the ColorBox object.
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, when a reference to a
subclass object is assigned to a superclass reference variable, you will have access only to those parts of
the object defined by the superclass. This is why plainbox can't access ‘j’ even when it refers to a
ColorBox object. If you think about it, this makes sense, because the superclass has no knowledge of
what a subclass adds to it. This is why the last line of code in the preceding fragment is commented out.
It is not possible for a Box reference to access the weight field, because it does not define one.
1
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
class Box
{
int width,height,depth;
Box() {width = height = depth = 0; }
// Box(int a,int b,int c) { width = a; height = b; depth = c; } // below and this line is same
Box(int a,int b,int c) { this.width = a; this.height = b; this.depth = c; }
}
The use of this is redundant, but perfectly correct. Inside Box( ), this will always refer to the invoking
object. While it is redundant in this case, this is useful in other contexts, one of which is explained in the
next section.
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);
Here, parameter-list specifies any parameters needed by the constructor in the superclass. super( ) must
always be the first statement executed inside a subclass' constructor.
To see how super( ) is used, consider this improved version of the ColorBox class:
// ColorBox now uses super to initialize its Box attributes.
class ColorBox extends Box
{
double weight; // weight of box
// initialize width, height, and depth using super()
ColorBoxWeight(double w, double h, double d, double m)
{
super(w, h, d); // call superclass constructor
weight = m;
}
}
2
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
● When a concrete class extends the LivingThing abstract class, it must implement the abstract method
walk(), or else, that subclass will also become an abstract class, and therefore cannot be instantiated.
Interfaces
● It defines a standard and public way of specifying the behavior of classes.
– Defines a contract
● All methods of an interface are abstract methods.
– Defines the signatures of a set of methods, without the body (implementation of the methods)
● A concrete class must implement the interface (all the abstract methods of the Interface).
● It allows classes, regardless of their locations in the class hierarchy, to implement common behaviors.
● If a class that implements an interface does not fully implement all its methods, then the class should
be declared as abstract.
● Variables in interfaces are nothing but shared constants.
● Interfaces can be extended, if you need to inherit interfaces.
● when you implement the interface methods, they should be public. this is because the signatures
should match!
● variables, if declared are implicitly static , final
●
3
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
Instance as a Type
● When you define a new interface, you are defining a new reference type
● You can use interface names anywhere you can use any other type name
● If you define a reference variable whose type is an interface, any object you assign to it must be an
instance of a class that implements the interface
● Let's say Person class implements PersonInterface interface
● You can do
– Person p1 = new Person();
– PersonInterface pi1 = p1;
– PersonInterface pi2 = new Person();
3 (a) Explain the private, protected and private protected modifiers in brief.
Answer:
Public Accessible by any class in any package.
Protected Accessible by the member's class, subclasses, or classes in the same package.
private Accessible only to the class in which it is declared.
<none> Is the default if no modifier is specified. Classes in the same package can access
this member.
4
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
The finally block executes at the end of its main block in all cases.
public class ZException
{
void go(int denom)
{
try
{
System.out.println(100/denom);
}
catch (ArithmeticException e)
{
System.out.println(0);
}
finally
{
System.out.println("Go complete");
}
}
5
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
obj.go(0);
obj.go(50);
}
}
finally creates a block of code that will be executed after a try/catch block has
completed and before the code following the try/catch block. The finally block will
execute whether or not an exception is thrown. If an exception is thrown, the finally block
will execute even if no catch statement matches the exception. Any time a method is
about to return to the caller from inside a try/catch block, via an uncaught exception or
an explicit return statement, the finally clause is also executed just before the method
returns. This can be useful for closing file handles and freeing up any other resources
that might have been allocated at the beginning of a method with the intent of disposing
of them before returning. The finally clause is optional. However, each try statement
requires at least one catch or a finally clause.
4. What are local applet and remote applet? How do applets differ from the application programs?
Answer: If the applet run on the same computer, called local applet. If the Applet run at server side, we
say it is remote applet.
Difference between Applet and application programs:-
An applet is basically designed for deploying on the web whereas an application is designed to
work as a standalone program.
Applets are created by extending the java.applet.Applet class.
There is no such constraint for an application
Applets run on any browser while
applications run using Java interpreter.
Execution of applets begin with the init() method while Execution of applications begins with
main() method.
Applet must contain at least one public class failing which the compiler reports an error. There it
is not mandatory to declare main( ) for an applet where as
In case of application, ‘main( )’ has to be included in a public class
Part of what goes on in a simple applet is the execution of the applet's life cycle. There are five
parts to this cycle, each of which has a matching method that you can override to gain access to
that cycle of the applet's life. The five stages of an applet's life cycle are listed here:
Initialization stage. This is the part of an applet's life cycle in which the applet object is
created and loaded. At this point, it's appropriate to create objects needed by the applet,
as well as initialize values that must be valid when the applet runs. The initialization
stage occurs only once in the applet's life cycle. You can tap into the initialization stage
by overriding the Applet class's init() method.
Start stage. This stage occurs when the system starts running the applet. The start stage
can occur right after the initialization stage or when an applet is restarted. This usually
happens when the user switches back to the applet's page after viewing a different page in
his or her Web browser. Unlike the initialization stage, the start stage can occur several
times over the life of the applet. To provide your own start code, override the Applet
class's start() method.
Paint stage. The paint stage occurs whenever the applet's display must be drawn on the
screen. This happens right after the applet's start stage, as well as whenever the applet's
display must be restored or changed. This can happen when the applet is exposed from
underneath another window or when the program changes the applet's display in some
way and explicitly repaints the applet. Almost every applet you write will have a
paint() method, which is the method you override to provide your applet with its
display.
Stop stage. As you may have guessed, the stop stage is the counterpart to the start stage.
Java executes this stage of the applet's life cycle when the applet is no longer visible on
the screen, such as when the user switches to a different Web page. The default behavior
for this cycle, however, is to keep the applet running in the background. If you want to
handle the stop cycle differently, you should override the Applet class's stop() method.
Destroy stage. This is the counterpart to the initialization stage and occurs when the
system is about to remove the applet from memory. Like the initialization cycle, the
destroy cycle occurs only once. If your applet has resources that need to be cleaned up
before the applet exits, this is the place to do it. You tap into this cycle by overriding the
7
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
7 (a) What are constructors? What is meant by constructor overloading? Explain with an example.
Answer: Java allows objects to initialize
themselves when they are created. This automatic initialization is performed through the
use of a constructor.
a) A constructor initializes an object immediately upon creation.
b) It has the same name as the class in which it resides and is syntactically similar to a method.
c) The constructor is automatically called immediately after the object is created, before the new
operator completes.
d) They have no return type, not even void.
Parameterized constructor: If constructor have different number and type of arguments. It is called
parameterized constructor. If in a class we need to define more than one constructor, we pass parameter
to constructors to make difference between them. For example,
Class Test
{
Test() {……..} // default constructor
Test(int a) {……} // one argument constructor
Test(int a, char c) {……..} // two argument constructor
Test(float f) {……..} // one different type argument constructor
}
8
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
7 (b)
8 (a) What is the difference between method overloading and overriding? Illustrate with an example.
Answer: In method overloading, we redefine the method in the same class with different number and/or
type of arguments. Whereas in function overriding, we redefine the method of base class in derived class
with same number and type of arguments. Overloading comes under static binding, but overriding comes
under dynamic binding. Example,
class Base
{
void method() {………..}
void method(int a) {……….} // redefining the method in same class. Overloading
}
class Derived extends Base
{
void method() {………} // redefining the method of base class in child class. Overriding.
}
8(c) Program
2007
2. Why main() method in java is declared as static? Why is a user defined applet class declared as
public?
Answer: To start main method without declaring any object. If we remove the static keyword from main, it
will compile but at runtime throws an error "NoSuchMethodError".
9
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
Objects are locked while their synchronized methods execute – No other threads are able to
access the object while it is locked.
public synchronized boolean deduct(float t) {
// code block associated
// with critical section...
}
When two threads are accessing the same object simultaneously, changes made by one will not
be seen by the other.
To prevent this from happening, certain methods are synchronized, allowing only one thread to
access the object at a time.
Example: – A bank account is accessed by a teller to withdraw $100. If the account is
synchronized, no other teller can access it until the first is finished and the account has been
updated.
If the synchronized method is static, a lock is obtained at the class level instead of the object
level. –Only one thread at a time may use such a method.
It is also possible to lock objects for an arbitrary block of code.
4. What is static inner class? Illustrate with an example. What is the utility of the collections API?
Answer: There are two types of nested classes: static and non-static.
The most important type of nested class is the inner class. An inner class is a non-static nested class. It
has access to all of the variables and methods of its outer class and may refer to them directly in the
same way that other non-static members of the outer class do. Thus, an inner class is fully within the
scope of its enclosing class.
The following program illustrates how to define and use an inner class. The class named
Outer has one instance variable named outer_x, one instance method named test( ),
and defines one inner class called Inner.
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
10
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
In the program, an inner class named Inner is defined within the scope of class Outer. Therefore, any
code in class Inner can directly access the variable outer_x. An instance method named display( ) is
defined inside Inner. This method displays outer_x on the standard output stream. The main( ) method
of InnerClassDemo creates an instance of class Outer and invokes its test( ) method. That method
creates an instance of class Inner and the display( ) method is called.
Somewhat surprisingly, the original impetus for Java was not the Internet! Instead, the primary motivation
was the need for a platform-independent (that is, architecture- neutral) language that could be used to
create software to be embedded in various consumer electronic devices, such as microwave ovens and
remote controls. As you can probably guess, many different types of CPUs are used as controllers. The
trouble with C and C++ (and most other languages) is that they are designed to be compiled for a specific
target. Although it is possible to compile a C++ program for just about any type of CPU, to do so requires
a full C++ compiler targeted for that CPU. The problem is that compilers are expensive and time-
consuming to create. An easier—and more cost-efficient—solution was needed. In an attempt to find
such a solution, Gosling and others began work on a portable, platform-independent language that could
be used to produce code that would run on a variety of CPUs under differing environments. This effort
ultimately led to the creation of Java.
class Dispatch {
public static void main(String args[]) {
A test;
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
test = b;
test.callme(); // calls B’s version of callme
test = c;
test.callme(); // calls C’s version of callme
test = a;
test.callme(); // calls A’s version of callme
}
}
OUTPUT:
Inside A's callme method
Inside B's callme method
Inside C's callme method
Inside B's callme method
Inside C's callme method
Inside A's callme method
c) Container class:-
The Container class is a subclass of Component. It has additional methods that allow other Component
objects to be nested within it. Other Container objects can be stored inside of a Container (since they
12
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
are themselves instances of Component). This makes for a multileveled containment system. A
container is responsible for laying out (that is, positioning) any components that it contains. It does this
through the use of various layout managers.
e) Exception handler:-
Introduced by Ada, adopted by C++ and Java.
Fix the previous problems.
It has overhead in execution time and memory resources.
Exception types:
Runtime exceptions, usually reported by Java VM runtime system
ArithmeticException
ArrayIndexOutOfBoundsException
ArrayStoreException
ClassCastException
IllegalArgumentException
IllegalMonitorStateException
IllegalThreadStateException
IndexOutOfBoundsException
NegativeArraySizeException
If a method body may throw a user exception, directly or indirectly, that is not processed in the
same method, the method must declare this fact with throws clause
void f() throws Exception1, Exception2 { …….}
e) Inter-thread communication:- There are two distinct types of multitasking:process-based and thread-
based. A process is, in essence, a program that is executing. Thus, process-based multitasking is the
feature that allows your computer to run two or more programs concurrently. In process-based
multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.
13
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This
means that a single program can perform two or more tasks simultaneously. For instance, a text editor
can format text at the same time that it is printing, as long as these two actions are being performed by
two separate threads. Thus, process-based multitasking deals with the "big picture," and thread-based
multitasking handles the details.
Multitasking threads require less overhead than multitasking processes. Processes are heavyweight
tasks that require their own separate address spaces. Interprocess communication is expensive and
limited. Context switching from one process to another is also costly. Threads, on the other hand, are
lightweight. They share the same address space and cooperatively share the same heavyweight process.
Interthread communication is inexpensive, and context switching from one thread to the next is low cost.
While Java programs make use of process-based multitasking environments, process-based multitasking
is not under the control of Java. However, multithreaded multitasking is.
Multithreading enables you to write very efficient programs that make maximum use of the CPU, because
idle time can be kept to a minimum. This is especially important for the interactive, networked
environment in which Java operates.
8. Provide a conceptual presentation of the applet life cycle. Develop a complete graph that
include all phases of the applet life cycle. What are the different attributes of applet tag? What is
Applet Viewer?
Answer: Different attributes of applet tag,
To include an applet on a Web page, <APPLET> tag is used!
<APPLET CODE=”Applet1.class” WIDTH=200 HEIGHT=50>
</APPLET>
CODE attributes the name of the class file containing the applet. This must be in the same
directory as the HTML file.
To use applets in a specific directory, CODEBASE is used
To pass parameters
A special parameter tag in the HTML file
<APPLET CODE=”Applet1.class” WIDTH=200 HEIGHT=50
<PARAM NAME= font VALUE=”TimesRoman”>
<PARAM NAME= size VALUE=”24”>
>
9. Program
10. a) Discuss about the Vector class. “Vector objects cannot store primitive type data directly.” Is it
true?
Answer: Vector implements a dynamic array. It is similar to ArrayList, but with two differences: Vector
is synchronized, and it contains many legacy methods that are not part of the collections framework. With
14
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
the release of Java 2, Vector was reengineered to extend AbstractList and implement the List interface,
so it now is fully compatible with collections.
Here are the Vector constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection c)
Vector defines these protected data members:
int capacityIncrement;
int elementCount;
Object elementData[ ]; [Reference: Java2 The complete reference: Herb Schildt]
The Vector class implements List interface, provides an order collection of elements of type Object (that
means any object and arrays, not data of primitive data types), and works similar to an array. [ Reference:
Debasish Jana, page 342].
10. b) What are wrapper classes? How can they be used to convert a data of primitive type to object
type?
Answer: Occassionally, we need to convert a primitive type like int to and object. All primitive types have
counterparts. For example, a class Integer corresponds to the primitive type int. These kinds of classes
are usually called wrappers. The wrapper classes have obvious names Integer, Long, Float, Double,
Short, Byte, Character, Void, and Boolen.(The first six inherit from the common superclass
java.lang.Number.) The wrappr has been constructed. They are also final, so you cannot subclass them.
Example,
class WrapperTest {
public static void main(String args[]) {
int a=2;
String s="23";
Integer i = new Integer(a);
int k=i.intValue();
int l=Integer.parseInt(s); // with i, it will be wrong.
System.out.println("The values of i is:"+i);
System.out.println("The values of k is:"+k);
System.out.println("The values of l is:"+l);
}
}
OUTPUT:
The values of i is:2
The values of k is:2
The values of l is:23
[Reference: Core Java, Volume1 Fundamentals by CAY S HORTSMANN & GARRY CORNELL]
10. (c) Write a program to implement a stack using the built in stack class in java.
Answer: Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack
only defines the default constructor, which creates an empty stack. Stack includes all the
methods defined by Vector, and adds several of its own, shown in Table.
Method Description
boolean empty() Returns true if the stack is empty, and returns false if the stack contains
elements.
Object peek() Returns the element on the top of the stack, but does not remove it.
Object pop() Returns the element on the top of the stack, removing it in the process.
Object push(Object element) Pushes element onto the stack. element is also returned.
int search(Object element) Searches for element in the stack. If found, its offset from the top of the
stack is returned. Otherwise, –1 is returned.
15
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
The following is the output produced by the program; notice how the exception handler
for EmptyStackException is caught so that you can gracefully handle a stack underflow:
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack
16
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
11. (a) What is an event? What is event handling? What is the role of event listeners in this regard?
Answer: In the delegation model, an event is an object that describes a state change in a source.
It can be generated as a consequence of a person interacting with the elements in a graphical user
interface. Some of the activities that cause events to be generated are pressing a button, entering a
character via the keyboard, selecting an item in a list, and clicking the mouse.
Many other user operations could also be cited as examples. Events may also occur that are not directly
caused by interactions with a user interface. For example, an event may be generated when a timer
expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed.
You are free to define events that are appropriate for your application.
Event handling and Event Listening: The modern approach to handling events is based on the
delegation event model. Its concept is quite simple: a source generates an event and sends it to one or
more listeners. In this scheme, the listener simply waits until it receives an event. Once received, the
listener processes the event and then returns. The advantage of this design is that the application logic
that processes events is cleanly separated from the user interface logic that generates those events.
11. (b) How can you pass parameter to an Applet from a HTML document?
Answer:
11. (c) Show by writing a complete code along with the output how multiple inheritance is
implemented in Java. Explain static import.
Answer: C++ allows one class to inherit two or more base classes at the same time. Java does not. To
understand the difference, consider the two hierarchies depicted here:
In both cases, subclass C inherits classes A and B. However, in the hierarchy on the left, C inherits both
A and B at the same time. In the one on the right, B inherits A, and C inherits B. By not allowing the
inheritance of multiple base classes by a single subclass, Java greatly simplifies the inheritance model.
Multiple inheritance carries with it several special cases that must be handled. This adds overhead to
both the compiler and the run-time system, while providing only marginal benefit for the programmer.
Program:
Starting with JDK5.0, the import statement has been enhanced to permit the importing of static methods
and fields, not just classes.
For example, if we add the directive
Import static java.lang.System.*;
to the top of our source file, then we can use static methods and fields of the System class without the
class name prefix:
out.println(“This is Anup\’s world!”); // i.e., System.out
exit(0); // i.e., System.out
17
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
2006
2. What is a thread? What are the two methods by which we may stop threads?
Answer: Threads are the set of steps or actions a program executes.
They allow multiple actions to occur at once
Threads do not carry all the process information data
Smallest unit of executable code that performs a task
An application can be divided into multiple tasks and each task can be assigned to a thread
Many threads executing simultaneously is termed as Multithreading
Although it may appear that the processes are running concurrently, it is not so.
3. What is an Interface? What are the major difference and similarities between an interface and a
class?
Answer: Interface:
Major difference between Interface and a class:
i) Interfaces never have instance fields.
ii) methods are never implemented in the interface.
iii) All methods of an interface are automatically public. A class can implement more than one
interface. By contrast, a class can only inherit a single superclass.
iv) An Interface lack the instance variables.
v) Variables in interfaces are implicitly “static” and “final”. They must also be initialized with a
constant value.
vi) Access in Interface is either public or not used.
4. How can a programmer define a class that cannot be inherited? Give an example.
Answer: To prevent a class from being inherited, precede the class declaration with final. Declaring a
class as final implicitly declares all of its methods as final, too. As you might expect, it is illegal to declare
a class as both abstract and final since an abstract class is incomplete by itself and relies upon its
subclasses to provide complete implementations.
18
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
As the comments imply, it is illegal for B to inherit A since A is declared as final.
5. What is object serialization in Java? Give an example where you can define function in the
interface.
Answer: object serialization:- The storage and retrieval of objects
7. Describe applet life cycle. Write a program to show all the steps of applet life cycle. What are
the different attribute of applet tag? What is remote applet?
Answer:
Applet Life Cycle:
Program:
Attribute of applet tag:
Remote Applet:
8. Describe life cycle. What do you mean by synchronized method? Write a program, which will
create a deadlock.
Answer:
9. (a) “Programmer can call a constructor from another constructor” – Explain with an example.
Answer:In java, a programmer can call a constructor from another constructor. It is done in inherited
class. For this we use an inbuilt method called super() from derived constructor which call the constructor
of the base class directly. Example,
class A
{
A() // constructor called when a new object of A will be created
{
System.out.println(―This is base class constructor.‖);
}
}
class B extends A
{
B() // constructor called when a new object will be created
{
super(); // calling the superclass A’s constructor.
System.out.println(―This is derived class constructor.‖);
}
}
Class SuperTest
{
public static void main(String args[])
{
19
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
Output:
This is base class constructor
This is derived class constructor
9. (b) Write a program tham draws a selected geographic shape in random colour and at random
location. The menu choices for the program are
Shape
Circle
Rectangle
Square
Answer:
10. (a) What is the difference between the inner class and nested class? Given an example for
both classes.
Answer:
10. (b) “In java variable are initialized before any method called even constructor” – Explain with
an example.
Answer: [page 44,
Motivation
Sometimes we want just a single instance of a class to exist in the system.
For example, we want just one window manager. Or just one factory for a family of products.
We need to have that one instance easily accessible.
And we want to ensure that additional instances of the class can not be created.
Structure
Consequences
Benefits
Controlled access to sole instance.
Permits a variable number of instances
20
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
11. What is polymorphism? What are all the types of polymorphism present in Java? Compare and
contrast overloading & overriding methods with proper examples.
Answer:
Polymorphism: Polymorphism is a feature that allows one interface to be used for a general class of
actions. The specific action is determined by the exact nature of the situation.
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.2);
System.out.println("Result of ob.test(123.2): " + result);
}
}
a and b: 10 20
double a: 123.2
Result of ob.test(123.2): 15178.24
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
2005
1 (a) Explain fundamental characteristics of OOP.
Answer: Fundamental characteristics of OOPs:
i) Encapsulation
ii) Inheritance
iii) Polymorphism
Encapsulation: - Encapsulation is the mechanism that binds together code and the data it manipulates,
and keeps both safe from outside interference and misuse. One way to think about encapsulation is as a
protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined
22
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
outside the wrapper. The power of encapsulated code is that everyone knows how to access it and thus
can use it regardless of the implementation details—and without fear of unexpected side effects.
Inheritance: - Inheritance is the process by which one object acquires the properties of another object.
This is important because it supports the concept of hierarchical classification. Inheritance interacts with
encapsulation as well. If a given class encapsulates some attributes, then any subclass will have the
same attributes plus any that it adds as part of its specialization.
Polymorphism: - It is a feature that allows one interface to be used for a general class of actions. The
specific action is determined by the exact nature of the situation. More generally, the concept of
polymorphism is often expressed by the phrase "one interface, multiple methods." This means that it is
possible to design a generic interface to a group of related activities. This helps reduce complexity by
allowing the same interface to be used to specify a general class of action. It is the compiler's job to select
the specific action (that is, method) as it applies to each situation.
The javac compiler creates a file called Example.class (for Exmaple.java) that contains the bytecode
version of the program. The Java bytecode is the intermediate representation of your program that
contains instructions the Java interpreter will execute. Thus, the output of javac is not code that can be
directly executed. To actually run the program, you must use the Java interpreter, called java.
By using this two technique together, many problem has solved for Java:-
a) Solve the major problems associated with downloading programs over the Internet.
b) Bytecode helps makes it much easier to run a program in a wide variety of environments.
1(d). Why do we declare a member variable method or class final? What are the advantages of
final class?
Answer: A variable can be declared as final. Doing so prevents its contents from being modified. This
means that you must initialize a final variable when it is declared.
A method can be declared as final. Doing so prevents this method to be overridden. We can not override
the final methods.
And we use final keyword with class to prevent a class to be inherited by other class. So, we can say final
class can not have any child class. Declaring a class as final implicitly declares all of its methods as final,
too.
Advantage of final class:
i) To make sure that the semantics can not be changed in a subclass.
ii) If the designer want to keep all type of changing authority in his/her hand. He/She can declare the
class as final class.
e.g. getTime and setTime methods of Calendar class are final. This indicates that the
designer of the Calendar class have taken over responsibility for the conversion between the
Date class and the calendar state. No subclass should be allowed to mess up this
arrangement. Similarly, the String class is final class. That means nobody can define a
subclass of String.
iii) If a method is not overridden,and it is short, then a compiler can optimize the method call away -
a process called inlining.
23
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
Anything declared private cannot be seen outside of its class. When a member does not have an explicit
access specification, it is visible to subclasses as well as to other classes in the same package. This is
the default access. If you want to allow an element to be seen outside your current package, but only to
classes that subclass your class directly, then declare that element protected.
Java includes the import statement to bring certain classes, or entire packages, into visibility.
24
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
The flow of execution stops immediately after the throw statement; any subsequent statements are not
executed.
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
Throws: If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. You do this by
including a throws clause in the method's declaration. A throws clause lists the types of exceptions that
a method might throw. This is necessary for all exceptions, except those of type Error or
RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be
declared in the throws clause. If they are not, a compile-time error will result.
25
Solved by Anup Prakash MCA(2007-10) batch, Student of Pailan college of Management and Technology, Kolkata(700104)
Errors: An Error signals that a non-recoverable error has occurred and should not be caught by the
programmer (NoSuchMethodError, OutOfMemoryError, StackOverflowError, VirtualMahcineError).
Exceptions: An Exception signals an abnormal condition that should be caught and handled by the
programmer.
All Errors and Exceptions have a String data field (Message) describing the condition. The String
Message can be retrieved with the getMessage() method, inherited from Throwable.
A RuntimeException (integer division by zero, array out-of-bounds, etc.) is usually a result of a
poorly written program. The program should be re-written instead of catching the
RuntimeException.
DataInputStreams: An input stream that contains methods for reading the Java standard data types. To
read binary values of the Java primitive types,we use DataInputStream.
DataInputStream implements the DataInput interface, which provides methods for reading all of Java’s primitive
types. These methods are shown in Table 10-6, and each can throw an IOException. DataInputStream uses an
InputStream instance as its foundation, overlaying it with methods that read the various Java data types. Remember
that DataInputStream reads data in its binary format, not its human-readable form. The constructor for
DataInputStream is shown here.
DataInputStream(InputStream inputStream)
Anonymous class:
a) String buffer class
27