Sei sulla pagina 1di 27

Subject Code: IMT-36

Subject Name : JAVA

PROGRAMMING
ASSIGNMENTS

PART A
Q1. Define each of the following terms: single inheritance, multiple inheritance, interface, superclass
and subclass.
Ans In object-oriented programming (OOP), inheritance is when an object or class is based on

another object or class, using the same implementation; it is a mechanism for code reuse. The
relationships of objects or classes through inheritance give rise to a hierarchy. Inheritance was
invented in 1967 for Simula.
Inheritance should not be confused with subtyping;[1] see Inheritance vs subtyping. In some
languages inheritance and subtyping agree,[a] while in others they differ; in general subtyping
establishes an is-a relationship, while inheritance only reuses implementation and establishes a
syntactic relationship, not necessarily a semantic relationship (inheritance does not
ensurebehavioral subtyping). To distinguish these concepts, subtyping is also known as interface
inheritance, while inheritance as defined here is known as implementation inheritance.
Inheritance is contrasted with object composition, where one object contains another object (or
objects of one class contain objects of another class); see composition over inheritance.
Composition implements a has-a relationship, in contrast to the is-a relationship of subtyping.
There are various types of inheritance, depending on paradigm and specific language. A
fundamental difference is whether one can inherit from only a single other object or class, which
is known as single inheritance, or whether one can inherit from multiple other objects or classes,
which is known as multiple inheritance. The hierarchy in single inheritance is a tree, while in
multiple inheritance it is a lattice.
Classical inheritance is used in class-based programming, where objects are defined
by classes, and classes can inherit attributes and implementation (i.e., previously coded
algorithms associated with a class) from pre-existing classes called base classes, superclasses,
or parent classes. The resulting classes are known as derived classes, subclasses, or child
classes, and the resulting hierarchy is known as a class hierarchy.
Differential inheritance is used in prototype-based programming, where objects inherit directly
from other objects.

Subclasses and superclasses


A Subclass, "derived class", heir class, or child class is a modular, derivative class that inherits
one or more language entities from one or more other classes (called superclasses, base
classes, or parent classes). The semantics of class inheritance vary from language to language,
but commonly the subclass automatically inherits the instance variables and member functions of
its superclasses. Some languages support the inheritance of other construct as well. For

example, in Eiffel, contracts which define the specification of a class are also inherited by heirs.
The superclass establishes a common interface and foundational functionality, which specialized
subclasses can inherit, modify, and supplement. The software inherited by a subclass is
consideredreused in the subclass. A reference to an instance of a class may actually be referring
one of its subclasses. The actual class of the object being referenced is impossible to predict
at compile-time. A uniform interface is used to invoke the member functions of objects of a
number of different classes. Subclass may replace superclass functions with entirely new
functions that must share the same method signature.

Uninheritable classes
In some languages a class may be declared as uninheritable by adding certain class modifiers to
the class declaration. Examples include the "final" keyword in Java or the "sealed" keyword inC#.
Such modifiers are added to the class declaration before the "class" keyword and the class
identifier declaration. Such sealed classes restrict reusability, particularly when developers only
have access to precompiled binaries and not source code.
The sealed class has no subclasses, so it can be easily deduced at compile time that references
or pointers to objects of that class are actually referencing instances of that class and not
instances of subclasses (they don't exist) or instances of superclasses (upcasting a reference
type violates the type system). subtype polymorphism. Because the exact type of the object
being referenced is known before execution, early binding (or "static dispatch") can be used
instead of late binding (also called "dynamic dispatch" or "dynamic binding") which requires one
or morevirtual method table lookups depending on whether multiple inheritance or only single
inheritance are supported in the programming language that is being used.

Methods that cannot be overridden


Just as classes may be sealed/finalized method declarations may contain method modifiers that
prevent the method from being overridden (i.e. replaced with a new function with the same name
and type signature in a subclass). A private method is unoverridable simply because it is not
accessible by classes other than the class it is a member function of. A "final" method in Java or
a "sealed" method in C#) cannot be overridden.

Virtual methods
If the superclass method is a virtual method, then invocations of the superclass method will
be dynamically dispatched. Some languages require methods to be specifically declared as
virtual (e.g.C++) and in others all methods are virtual (e.g. Java). An invocation of a non-virtual
method will always be statically dispatched (i.e. the address of the function call is determined at
compile-time). Static dispatch is faster than dynamic dispatch and allows optimisations such
as inline expansion.
Q2. Discuss why casting a superclass reference to a subclass reference is potentially dangerous
multiple inheritance? What feature of Java helps realize the benefits of multiple inheritance?
Ans Multiple inheritance is a feature of some object-oriented computer programming

languages in which an object or class can inherit characteristics and features from more than one
parent object or parent class. It is distinct from single inheritance, where an object or class may
only inherit from one particular object or class.

Multiple inheritance has been a touchy issue for many years, with opponents pointing to its
increased complexity and ambiguity in situations such as the "diamond problem", where it may
be ambiguous as to which parent class a particular feature is inherited from if more than one
parent class implements said feature. This can be addressed in various ways, including
using virtual inheritance.[1] Alternate methods of object composition not based on inheritance
such as mixins and traits have also been proposed to address the ambiguity.
The "diamond problem" (sometimes referred to as the "deadly diamond of death" [3]) is an
ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B
and C. If there is a method in A that B and/or C has overridden, and D does not override it, then
which version of the method does D inherit: that of B, or that of C?
For example, in the context of GUI software development, a class Button may inherit from both
classes Rectangle (for appearance) andClickable (for functionality/input handling), and
classes Rectangle and Clickable both inherit from the Object class. Now if
the equalsmethod is called for a Button object and there is no such method in
the Button class but there is an overridden equals method in Rectangle orClickable (or
both), which method should be eventually called?
It is called the "diamond problem" because of the shape of the class inheritance diagram in this
situation. In this case, class A is at the top, both B and C separately beneath it, and D joins the
two together at the bottom to form a diamond shape.

Mitigation
Languages have different ways of dealing with these problems of repeated inheritance.

C++ by default follows each inheritance path separately, so a D object would actually
contain two separate A objects, and uses of A's members have to be properly qualified. If the
inheritance from A to B and the inheritance from A to C are both marked "virtual" (for
example, "class B : virtual public A"), C++ takes special care to only create
one A object, and uses of A's members work correctly. If virtual inheritance and nonvirtual
inheritance are mixed, there is a single virtual A and a nonvirtual A for each nonvirtual
inheritance path to A. C++ requires stating explicitly which parent class the feature to be
used is invoked from i.e. "Worker::Human.Age". C++ does not support explicit repeated
inheritance since there would be no way to qualify which superclass to use (i.e. having a
class appear more than once in a single derivation list [class Dog : public Animal, Animal]).
C++ also allows a single instance of the multiple class to be created via the virtual
inheritance mechanism (i.e. "Worker::Human" and "Musician::Human" will reference the
same object).

Common Lisp CLOS attempts to provide both reasonable default behavior and the ability
to override it. By default, the method with the most specific argument classes is chosen; then
in the order in which parent classes are named in the subclass definition. However, the
programmer can override this, by giving a specific method resolution order or stating a rule
for combining methods. This is called method combination, which may be fully controlled.
The MOP (metaobject protocol) also provides means to modify the inheritance, dynamic

dispatch, class instantiation, and other internal mechanisms without affecting the stability of
the system.

Curl allows only classes that are explicitly marked as shared to be inherited repeatedly.
Shared classes must define a secondary constructor for each regular constructor in the
class. The regular constructor is called the first time the state for the shared class is
initialized through a subclass constructor, and the secondary constructor will be invoked for
all other subclasses.

In Eiffel, the ancestors' methods to use are specified explicitly with select and rename
directives. This allows the methods of the base class to be shared between its descendants
or to even give each of them a separate copy of the base class. Eiffel allows explicitly joining
or separating features that are being inherited from superclasses. Eiffel will automatically join
features together, if they have the same name and implementation. The class writer has the
option to rename the inherited features to separate them. Eiffel also allows explicit repeated
inheritance such as A: B, B.

Java 8 introduces default methods on interfaces. If A,B,C are interfaces, B,C can each
provide a different implementation to an abstract method of A, causing the diamond problem.
Either class D must reimplement the method (the body of which can simply forward the call to
one of the super implementations), or the ambiguity will be rejected as a compile error. [4]

JavaFX Script in version 1.2 allows multiple inheritance through the use of mixins. In
case of conflict, the compiler prohibits the direct usage of the ambiguous variable or function.
Each inherited member can still be accessed by casting the object to the mixin of interest,
e.g. (individual as Person).printInfo();.

Logtalk supports both interface and implementation multi-inheritance, allowing the


declaration of method aliases that provide both renaming and access to methods that would
be masked out by the default conflict resolution mechanism.

Q3. Distinguish between non-abstract methods and abstract methods.


Ans non-abstract methods in abstract classes will be called when it's concrete subclass calls

super() if it is overridden. So there are multiple possibilities. If method is not overridden then
the super class method will be executed. if we use super() in the concrete subclass method
then the overridden method with the super class method will be executed.
Where as Java 8 interface default methods are completely different. It provided a choice to
the developers to implement the method in the implementing class or not. If the function is
not implementedthen and only then the default method will be executed.
Possible Use Case :
The most important use case for this new feature in the JDK libraries is the possibility to
extend existing interfaces without breaking existing implementers: adding a new abstract

method to an interface would require all implementing classes to implement that new
method.

An abstract class is a class that is declared abstractit may or may not include
abstract methods. Abstract classes cannot be instantiated, but they can be
subclassed.
An abstract method is a method that is declared without an implementation
(without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, the class itself must be declared abstract, as
in:
public abstract class GraphicObject {
// declare fields
// declare non-abstract methods
abstract void draw();
}

Abstract Classes versus Interfaces


Unlike interfaces, abstract classes can contain fields that are not static and final,
and they can contain implemented methods. Such abstract classes are similar to
interfaces, except that they provide a partial implementation, leaving it to
subclasses to complete the implementation. If an abstract class
contains only abstract method declarations, it should be declared as an interface
instead.
Multiple interfaces can be implemented by classes anywhere in the class hierarchy,
whether or not they are related to one another in any way. Think
of Comparable orCloneable, for example.
By comparison, abstract classes are most commonly subclassed to share pieces of
implementation. A single abstract class is subclassed by similar classes that have a
lot in common (the implemented parts of the abstract class), but also have some
differences (the abstract methods).
An Abstract Class Example
In an object-oriented drawing application, you can draw circles, rectangles, lines,
Bezier curves, and many other graphic objects. These objects all have certain states
(for example: position, orientation, line color, fill color) and behaviors (for
example: moveTo, rotate, resize, draw) in common. Some of these states and
behaviors are the same for all graphic objectsfor example: position, fill color,
and moveTo. Others require different implementationsfor example, resize or

draw. All GraphicObjects must know how to draw or resize themselves; they just
differ in how they do it. This is a perfect situation for an abstract superclass. You
can take advantage of the similarities and declare all the graphic objects to inherit
from the same abstract parent objectfor example, GraphicObject, as shown in the
following figure.

Classes Rectangle, Line, Bezier, and Circle inherit from


GraphicObject

First, you declare an abstract class, GraphicObject, to provide member variables


and methods that are wholly shared by all subclasses, such as the current position
and themoveTo method. GraphicObject also declares abstract methods for methods,
such as draw or resize, that need to be implemented by all subclasses but must be
implemented in different ways. The GraphicObject class can look something like
this:

Q4. Write a recursive method power (base, exponent) that when invoked returns base exponent
Ans Recursive

power Method) Write a recursive method power( base, exponent )

that, when
called, returns
base exponent
For example, power( 3,4 ) = 3 * 3 * 3 * 3. Assume that exponent is an integer
greater than
or equal to 1. (Hint: The recursion step should use the relationship
base exponent = base base exponent 1
and the terminating condition occurs when exponent is equal to 1, because
base1 = base
Incorporate this method into a program that enables the user to enter the base
and exponent

// Exercise 15.9 Solution: Power.java


2 // Program calculates an exponent.
34

public class Power


5{
6 // recursively calculate value of exponent
7 public int integerPower( int base, int exponent )
8{
9 if ( exponent == 1 )
10 return base;
11 else
12 return base * integerPower( base, exponent - 1 );
13
14 } // end method integerPower
15 } // end class Power

// Exercise 15.9 Solution: PowerTest.java


2 // Testing the program that calculates an exponent.
3 import java.util.Scanner;
45
public class PowerTest
6{
7 // get user input and calculate number
8 public static void main( String args[] )
9{
10 Power power = new Power();
11 Scanner scanner = new Scanner( System.in );
12
13 System.out.print( "Enter base: " );
14
15 // get base from user
16 int base = scanner.nextInt();
17
18 System.out.print( "Enter exponent: " );
// get exponent from user
21 int exponent = scanner.nextInt();
22
23 // raise to exponent if appropriate

24 if ( exponent > 0 )
25 {
26 int result = power.integerPower( base, exponent );
27 System.out.printf( "Value is %d", result );
28 }
29 else
30 System.out.print( "Invalid Exponent." );
31
32 } // end main
33 } // end class PowerTest
Q5. Selection sort searches an array for the smallest element in the array. Then, the smallest element
is swapped with the first element of the array. The process is repeated for the subarray beginning with
the second element of the array. Each pass of the array results in one element being placed in its
proper location. This sort has a performance comparably to the bubble sort-for an array n elements,
n-1 passes must be made, and for each subarray, n-1 comparisons must be made to find the
smallest value. When the subarray being processed contains one element, the array is sorted. Write
a recursive method selection Sort to perform this algorithm.
Ans A selection sort searches an array looking for the smallest element in the array.

Then, the smallest element is swapped with the first element of the array. The
process is repeated for the subarray beginning with the second element of the array.
Each pass of the array results in one element being placed in its proper
location.This sort performs comparably to the bubble sort - for an array
of n elements, n-1 passes must be made, and for each subarray, n-1 comparisons
must be made to find the smallest value, but unlike the Bubble sort only one swap
will be done for each pass.When the subarray contains one element, array is sorted.
Develop a C++ program that uses the selection sort algorithm to sort an array of integers. A
selection sort searches an array looking for the smallest element. Then, the smallest element is
swapped with the first element of the array. The process is repeated for the sub-array beginning
with the second element of the array. Each pass of the array results in one element being placed
in its proper location. This sort performs comparably to the insertion sort---for an array of n
elements, n 1 passes must be made, and for each sub-array, n 1 comparisons must be made
to find the smallest value. When the sub-array being processed contains one element, the array
is sorted. Your one function, named selectionSort, must use recursion to sort the array. (OK, if
you cannot solve it recursively, some credit will be given for solving it non-recursively.) A selection
sort searches an array looking for the smallest element in the array. Then,
the smallest element is swapped with the first element of the array. The process is
repeated for the subarray beginning with the second element of the array. Each pass

of the array results in one element being placed in its proper location. This sort
performs comparably to the bubble sortfor an array of n elements, n - 1 passes must
be made, and for each subarray, n - 1 comparisons must be made to find the smallest
value. When the subarray being processed contains one element, the array is sorted.

Write two functions IterSort and RecSort that implement the selection sort
algorithm described in 4.31. Function IterSort implements it using iterative approach
whereas function RecSort implements it using recursion. In the main program, you
should create an array of pointers to the two functions For user interface, your program should
print the menus as follows:

Menu
[1] Iterative Sort (Generate 10 numbers randomly between 1 and 100)
[2] Recursive Sort (Generate 10 numbers randomly between 1 and 100)
[3] Iterative Sort (User inputs 10 numbers between 1 and 100)
[4] Recursive Sort (User inputs 10 numbers between 1 and 100)

Enter Choice: <user will enter a number between 1 and 4>

If the user chooses a 1 or 2, your program should generate 10 random numbers


between 1 and 100. Use srand() function to generate the random numbers - refer to
example given in pages 186-189.

If the user inputs choices 3 or 4, the program should ask the user to input 10 numbers
that are less than 100 - make sure you catch wrong inputs

PART B
1. Create a Data class with the following capabilities:
(a) Output the date in multiple formats such as
MM/DD/YY
June 14,2009
DDD YYYY
(b) Use overload constructors to create Date objects initialized with dates of the formats in part
Ans a)b)
import java.util.Calendar;
02
import java.util.GregorianCalendar;
03
04
05
06

public class date {

07
08

private GregorianCalendar date = null;

09 private String[] months = new String[]


{ "january", "february", "march", "april", "may",
"june", "july", "august", "september", "
1
0 october","november", "december" };
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

public MultiDate(int month, int day, int year) {


date = new GregorianCalendar(year, month-1, day);
}
public MultiDate(String month, int day, int year) {
date = new GregorianCalendar(year, this.getMonth(month), day);
}
public MultiDate(int dayOfYear, int year) {
date = new GregorianCalendar();
date.set(Calendar.DAY_OF_YEAR, dayOfYear);
date.set(Calendar.YEAR, year);
}
private int getMonth(String month) {

27

for (int i=0; i<months.length; ++i)

28

if (month.toLowerCase().equals(months)) //equals(months))

29
30
31

return i;
return 0;
}

32
33

public String toString() {

return date.get(Calendar.MONTH)+1 + "-" + date.get(Calendar.DATE)


+ "-" + date.get(Calendar.YEAR);
35
}
36
34

37
38
39
40
41
42
43
44
45
46
47
48

public static void main(String[] args) {


MultiDate a = new MultiDate(9, 16, 2009);
MultiDate b = new MultiDate("September", 16, 2009);
MultiDate c = new MultiDate(259, 2009);
// all three dates above are equal and will therefore print
// the same dates
System.out.println(a);
System.out.println(B)/>;
System.out.println(c);
}

Q2. Create class Saving Account. Use a static class variable to store the annual interest Rate for each
of the savers. Each object of the class contains a private instance variable savings Balance indicating
the amount the saver currently has on deposit. Provide method Calculate Monthly Interest to calculate
the monthly interest by multiplying the balance by annual interest Rate divided by 12; this interest
should be added to saving Balance. Provide a static method modify Interest Rate that sets the annual
interest Rate to a new value. Write a driver program to test class Savings Account object, saver1 and
saver2, with balance of $2000.00 and $3000.00, respectively. Set annual interest Rate to 4%, then
calculate the monthly interest and print the new balances for each of the savers. Then set the annual
interest Rate to5% and calculate the next month's interest and print the new balances for each of the
savers.
Ans
01
public class SavingsAccount
02
{
03
private static double annualInterestRate;
04

private double savingsBalance;

05
06
07
08
09
10
11

protected SavingsAccount()
{
savingsBalance = 0;
annualInterestRate = 0;
}

12
13
14
15
16
17

protected SavingsAccount(double balance)


{
savingsBalance = balance;
annualInterestRate = 0;
}

18
19
20

protected void calculateMonthlyInterest()


{
System.out.println("Current savings balance: " +

savingsBalance);
21
22
23
#

double monthlyInterest;
monthlyInterest = (savingsBalance * annualInterestRate)/12;
savingsBalance += monthlyInterest;

3. Explain the advantage of object oriented model over traditional programming model.
Ans Benefits

of Object-Oriented Approach

Object-oriented databases make the promise of reduced maintenance, code reusability, real
world modeling, and improved reliability and flexibility. However, these are just promises
and in the real world some users find that the object-oriented benefits are not as compelling
as they originally believed. For example, what is code reusability? Some will say that they
can reuse much of the object-oriented code that is created for a system, but many say there is
no more code reusability in object-oriented systems than in traditional systems. Code
reusability is a subjective thing, and depends heavily on how the system is defined. The
object-oriented approach does give the ability to reduce some of the major expenses
associated with systems, such as maintenance and development of programming code. Here
are some of the benefits of the object-oriented approach:
Reduced Maintenance: The primary goal of object-oriented development is the assurance
that the system will enjoy a longer life while having far smaller maintenance costs. Because
most of the processes within the system are encapsulated, the behaviors may be reused and
incorporated into new behaviors.
Real-World Modeling: Object-oriented system tend to model the real world in a more
complete fashion than do traditional methods. Objects are organized into classes of objects,
and objects are associated with behaviors. The model is based on objects, rather than on data
and processing.
Improved Reliability and Flexibility: Object-oriented system promise to be far more
reliable than traditional systems, primarily because new behaviors can be "built" from
existing objects. Because objects can be dynamically called and accessed, new objects may
be created at any time. The new objects may inherit data attributes from one, or many other
objects. Behaviors may be inherited from super-classes, and novel behaviors may be added
without effecting existing systems functions.
High Code Reusability: When a new object is created, it will automatically inherit the data
attributes and characteristics of the class from which it was spawned. The new object will
also inherit the data and behaviors from all superclasses in which it participates. When a user
creates a new type of a widget, the new object behaves "wigitty", while having new behaviors
which are defined to the system.
The downside of the Object Technology
There are several major misconceptions which must be addressed when considering the use
of an object-oriented method:
Object-oriented Development is not a panacea - Object-oriented Development is best
suited for dynamic, interactive environments, as evidenced by its widespread acceptance in

CAD/CAM and engineering design systems. Wide-scale object-oriented corporate systems


are still unproved, and many bread-and-butter information systems applications (i.e. payroll,
accounting), may not benefit from the object-oriented approach.
Object-oriented Development is not a technology - Although many advocates are religious
in their fervor for object-oriented systems, remember that all the "HOOPLA" is directed at
the object-oriented approach to problem solving, and not to any specific technology.
Object-oriented Development is not yet completely accepted by major vendors - Objectoriented Development has gained some market respectability, and vendors have gone from
catering to a "lunatic fringe" to a respected market. Still, there are major reservations as to
whether Object-oriented development will become a major force, or fade into history, as in
the 1980's when Decision Support Systems made great promises, only to fade into obscurity.
Cannot find qualified programmers and DBAs
When one investigates the general acceptance of object-oriented systems in the commercial
marketplace, you generally find that most managers would like to see an object technology
approach, but they do not have the time to train their staffs in object-oriented methods. Other
will say that the object-oriented method is only for graphical workstation systems, and that
there is no pressing need for object-oriented system within mainstream business systems.
Even though commercial object-oriented programming languages have been on the market
for several years, systems written with object-oriented languages comprise less than 1% of
systems today.

Q4. Define each of the following terms: single inheritance, multiple inheritance, interface, superclass
and subclass.
Ans inheritance is when an object or class is based on another object or class, using the same

implementation; it is a mechanism for code reuse. The relationships of objects or classes through
inheritance give rise to a hierarchy. Inheritance was invented in 1967 for Simula.[citation needed]
Inheritance should not be confused with subtyping;[1] see Inheritance vs subtyping. In some
languages inheritance and subtyping agree,[a] while in others they differ; in general subtyping
establishes an is-a relationship, while inheritance only reuses implementation and establishes a
syntactic relationship, not necessarily a semantic relationship (inheritance does not
ensurebehavioral subtyping). To distinguish these concepts, subtyping is also known as interface
inheritance, while inheritance as defined here is known as implementation inheritance.
Inheritance is contrasted with object composition, where one object contains another object (or
objects of one class contain objects of another class); see composition over inheritance.
Composition implements a has-a relationship, in contrast to the is-a relationship of subtyping.

Types of inheritance

There are various types of inheritance, depending on paradigm and specific language. A
fundamental difference is whether one can inherit from only a single other object or class, which
is known as single inheritance, or whether one can inherit from multiple other objects or classes,
which is known as multiple inheritance. The hierarchy in single inheritance is a tree, while in
multiple inheritance it is a lattice.
Classical inheritance is used in class-based programming, where objects are defined
by classes, and classes can inherit attributes and implementation (i.e., previously coded
algorithms associated with a class) from pre-existing classes called base classes, superclasses,
or parent classes. The resulting classes are known as derived classes, subclasses, or child
classes, and the resulting hierarchy is known as a class hierarchy.
Differential inheritance is used in prototype-based programming, where objects inherit directly
from other objects.

Subclasses and superclasses


A Subclass, "derived class", heir class, or child class is a modular, derivative class that inherits
one or more language entities from one or more other classes (called superclasses, base
classes, or parent classes). The semantics of class inheritance vary from language to language,
but commonly the subclass automatically inherits the instance variables and member functions of
its superclasses. Some languages support the inheritance of other construct as well. For
example, in Eiffel, contracts which define the specification of a class are also inherited by heirs.
The superclass establishes a common interface and foundational functionality, which specialized
subclasses can inherit, modify, and supplement. The software inherited by a subclass is
consideredreused in the subclass. A reference to an instance of a class may actually be referring
one of its subclasses. The actual class of the object being referenced is impossible to predict
at compile-time. A uniform interface is used to invoke the member functions of objects of a
number of different classes. Subclass may replace superclass functions with entirely new
functions that must share the same method signature.

Uninheritable classes
In some languages a class may be declared as uninheritable by adding certain class modifiers to
the class declaration. Examples include the "final" keyword in Java or the "sealed" keyword inC#.
Such modifiers are added to the class declaration before the "class" keyword and the class
identifier declaration. Such sealed classes restrict reusability, particularly when developers only
have access to precompiled binaries and not source code.
The sealed class has no subclasses, so it can be easily deduced at compile time that references
or pointers to objects of that class are actually referencing instances of that class and not
instances of subclasses (they don't exist) or instances of superclasses (upcasting a reference
type violates the type system). subtype polymorphism. Because the exact type of the object
being referenced is known before execution, early binding (or "static dispatch") can be used
instead of late binding (also called "dynamic dispatch" or "dynamic binding") which requires one

or morevirtual method table lookups depending on whether multiple inheritance or only single
inheritance are supported in the programming language that is being used.

Q5. Discuss why casting a superclass reference to a subclass reference is potentially dangerous
multiple inheritance? What feature of Java helps realize the benefits of multiple inheritance?
Ans Multiple inheritance is a feature of some object-oriented computer programming

languages in which an object or class can inherit characteristics and features from more than one
parent object or parent class. It is distinct from single inheritance, where an object or class may
only inherit from one particular object or class.
Multiple inheritance has been a touchy issue for many years, with opponents pointing to its
increased complexity and ambiguity in situations such as the "diamond problem", where it may
be ambiguous as to which parent class a particular feature is inherited from if more than one
parent class implements said feature. This can be addressed in various ways, including
using virtual inheritance.[1] Alternate methods of object composition not based on inheritance
such as mixins and traits have also been proposed to address the ambiguity.

The diamond problem

A diamond class inheritance diagram.

The "diamond problem" (sometimes referred to as the "deadly diamond of death" [3]) is an
ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B
and C. If there is a method in A that B and/or C has overridden, and D does not override it, then
which version of the method does D inherit: that of B, or that of C?

For example, in the context of GUI software development, a class Button may inherit from both
classes Rectangle (for appearance) andClickable (for functionality/input handling), and
classes Rectangle and Clickable both inherit from the Object class. Now if
the equalsmethod is called for a Button object and there is no such method in
the Button class but there is an overridden equals method in Rectangle orClickable (or
both), which method should be eventually called?
It is called the "diamond problem" because of the shape of the class inheritance diagram in this
situation. In this case, class A is at the top, both B and C separately beneath it, and D joins the
two together at the bottom to form a diamond shape.

Mitigation
Languages have different ways of dealing with these problems of repeated inheritance.

C++ by default follows each inheritance path separately, so a D object would actually
contain two separate A objects, and uses of A's members have to be properly qualified. If the
inheritance from A to B and the inheritance from A to C are both marked "virtual" (for
example, "class B : virtual public A"), C++ takes special care to only create
one A object, and uses of A's members work correctly. If virtual inheritance and nonvirtual
inheritance are mixed, there is a single virtual A and a nonvirtual A for each nonvirtual
inheritance path to A. C++ requires stating explicitly which parent class the feature to be
used is invoked from i.e. "Worker::Human.Age". C++ does not support explicit repeated
inheritance since there would be no way to qualify which superclass to use (i.e. having a
class appear more than once in a single derivation list [class Dog : public Animal, Animal]).
C++ also allows a single instance of the multiple class to be created via the virtual
inheritance mechanism (i.e. "Worker::Human" and "Musician::Human" will reference the
same object).

Common Lisp CLOS attempts to provide both reasonable default behavior and the ability
to override it. By default, the method with the most specific argument classes is chosen; then
in the order in which parent classes are named in the subclass definition. However, the
programmer can override this, by giving a specific method resolution order or stating a rule
for combining methods. This is called method combination, which may be fully controlled.
The MOP (metaobject protocol) also provides means to modify the inheritance, dynamic
dispatch, class instantiation, and other internal mechanisms without affecting the stability of
the system.

Curl allows only classes that are explicitly marked as shared to be inherited repeatedly.
Shared classes must define a secondary constructor for each regular constructor in the
class. The regular constructor is called the first time the state for the shared class is
initialized through a subclass constructor, and the secondary constructor will be invoked for
all other subclasses.

In Eiffel, the ancestors' methods to use are specified explicitly with select and rename
directives. This allows the methods of the base class to be shared between its descendants

or to even give each of them a separate copy of the base class. Eiffel allows explicitly joining
or separating features that are being inherited from superclasses. Eiffel will automatically join
features together, if they have the same name and implementation. The class writer has the
option to rename the inherited features to separate them. Eiffel also allows explicit repeated
inheritance such as A: B, B.

PART C
Q1. Distinguish between non-abstract methods and abstract methods.
Ans non-abstract methods in abstract classes will be called when it's concrete subclass calls

super() if it is overridden. So there are multiple possibilities. If method is not overridden then
the super class method will be executed. if we use super() in the concrete subclass method
then the overridden method with the super class method will be executed.
Where as Java 8 interface default methods are completely different. It provided a choice to
the developers to implement the method in the implementing class or not. If the function is
not implementedthen and only then the default method will be executed.
Possible Use Case :
The most important use case for this new feature in the JDK libraries is the possibility to
extend existing interfaces without breaking existing implementers: adding a new abstract
method to an interface would require all implementing classes to implement that new
method

Q2. a) What is Package.


b) Explain Client Server.
Ans a) A package is a namespace

that organizes a set of related classes and


interfaces. Conceptually you can think of packages as being similar to different
folders on your computer. You might keep HTML pages in one folder, images in
another, and scripts or applications in yet another. Because software written in the
Java programming language can be composed of hundreds or thousands of
individual classes, it makes sense to keep things organized by placing related
classes and interfaces into packages.
The Java platform provides an enormous class library (a set of packages) suitable
for use in your own applications. This library is known as the "Application
Programming Interface", or "API" for short. Its packages represent the tasks most
commonly associated with general-purpose programming. For example,
a String object contains state and behavior for character strings; a File object
allows a programmer to easily create, delete, inspect, compare, or modify a file on
the filesystem; a Socket object allows for the creation and use of network sockets;

various GUI objects control buttons and checkboxes and anything else related to
graphical user interfaces. There are literally thousands of classes to choose from.
This allows you, the programmer, to focus on the design of your particular
application, rather than the infrastructure required to make it work.
A package is a mechanism for organizing Java classes into namespaces similar to the modules
of Modula. Java packages can be stored in compressed files called JAR files, allowing classes to
download faster as a group rather than one at a time. Programmers also typically use packages
to organize classes belonging to the same category or providing similar functionality.

A package provides a unique namespace for the types it contains.

Classes in the same package can access each other's package-access members

b) Client-Server networking is a paradigm which is most commonly

used in networking the world over. As the name makes pretty clear, the
definition of a client server network is that one of the involved parties
acts as a client and the other acts as a server. he clientserver model,
or clientserver architecture, is an approach to computer network programming in
which computers in a network assume one of two roles: The server selectively shares
its resources, and the client initiates contact with a server in order to use those resources.[1]
The clientserver model is prevalent in computer networks. Email, network printing, and
the World Wide Web all apply the clientserver model. Clients and servers exchange messages
in a request-response messaging pattern: The client sends a request, and the server returns a
response. This exchange of messages is an example ofinter-process communication. To
communicate, the computers must have a common language, and they must follow rules so that
both the client and the server know what to expect. The language and rules of communication
are defined in a communications protocol. All client-server protocols operate in the application
layer. The application-layer protocol defines the basic patterns of the dialogue. To formalize
exchange data even further, the server may implement an API (such as a web service).[2] The
API is an abstraction layer for such resources as databases and custom software. By restricting
communication to a specific content format, it facilitates parsing. By abstracting access, it
facilitates cross-platform data exchange.[3]
A server may receive requests from many different clients in a very short period of time. Because
the computer can perform a limited number of tasks at any moment, it relies on
a schedulingsystem to prioritize incoming requests from clients in order to accommodate them all
in turn. To prevent abuse and maximize uptime, the server's software limits how a client can use
the server's resources. Even so, a server is not immune from abuse. A denial of service
attack exploits a server's obligation to process requests by bombarding it with requests
incessantly. This inhibits the server's ability to responding to legitimate requests.

Q3. a) What is LRL?


b) Why has Java gained international acceptance.
Ans a) The Lunar Receiving Laboratory (LRL) was a facility at NASA's Lyndon B. Johnson

Space Center (Building 37) that was constructed to quarantineastronauts and material brought
back from the Moon during the Apollo program to mitigate the risk of back-contamination. After
recovery at sea, crews from Apollo 11, Apollo 12 and Apollo 14 walked from their helicopter to an
isolation van on the deck of an aircraft carrier and were brought to the LRL for quarantine.
Samples of rock and regolith that the astronauts collected and brought back were flown directly
to the LRL and initially analyzed in gloveboxvacuum chambers The quarantine requirement was
dropped beginning with Apollo 15 and the LRL was used for study, distribution and safe storage
of the lunar samples. Between 1969 and 1972, six Apollo space flight missions brought back 382
kilograms (842 pounds) of lunar rocks, core samples, pebbles, sand and dust from the lunar
surface. The six space flights returned 2200 separate samples from six different exploration sites
on the lunar surface. (Other lunar samples were returned to Earth by three automated Soviet
spacecraft, named Luna 16, Luna 20, and Luna 24, which returned samples totaling 300 grams
(approximately 3/4 pound) from three other lunar sites.)
In 1976, a portion of the samples were moved to Brooks Air Force Base in San Antonio, Texas for
second-site storage. In 1979, a Lunar Sample Laboratory Facility was built to serve as the chief
repository for the Apollo samples. It was constructed to provide permanent storage of the lunar
sample collection in a physically secure and non-contaminating environment. The facility consists
of storage vaults for the samples, laboratories for sample preparation and study, a vault for
sample data and records, and machinery to supply nitrogen to the cabinets in which the samples
are stored and processed. [1] The Lunar Receiving Laboratory building is currently occupied by
the Life Sciences division. It contains biomedical and environment labs, and is used for
experiments involving human adaptation to microgravity.
b) Avani Cimcon Technologies (ACT) is one of the pioneers in developing applications in Java
technologies. Our core strategy for Java Development is to develop a robust and a versatile generic
framework that allows us to build business centric applications. In the development of this framework we
have utilized our vast and varied experience gained over a number of years by developing software and
products for different customers from all over the world. The other key strategy has been to invest in
training and gaining expertise on industry standard development platforms available in Java such as
Weblogic and IBM Websphere.
We have invested time in architecting, designing, developing and testing the Java Framework. An
experienced and a dedicated team have enabled us to create this framework in a short period of time.
ACTJava Framework is robust and flexible and addresses specific types of work that an organization
undertakes.
For maintenance, ACTs resource pool has experienced senior programmers, who maintain and enhance
theJava Framework, always in a secured environment.
The advantages of this Framework are listed below:

Re-usability of Code

Rapid Development

Designers and Developers can work simultaneously

Changes in the Layout

Changes in Business Logic

Recursive Processing

Dynamic Content

Web Services

Q4. a) Explain Java API.


b) Explain RMI with suitable example.
Ans a) There are 3 types of Java Programming Language Application Programming Interfaces

(APIs) :

the official core Java API, contained in the JDK or JRE, of one of the editions of the Java
Platform. The three editions of the Java Platform are Java ME (Micro edition), Java SE
(Standard edition), and Java EE (Enterprise edition).

optional official APIs that can be downloaded separately. The specification of these APIs
are defined according to a Java Specification Request (JSR), and sometimes some of these
APIs are later included in the core APIs of the platform (the most notable example of this kind
is Swing).

unofficial APIs, developed by third parties, but not related to any JSRs.

Third-parties can freely implement any JSR specifications for an official API (even for the core
API of the language), providing that they conform to the Technology Compatibility Kit (TCK) for
this JSR (the TCK is a suite of tests that checks conformance of implementations for a JSR). The
result of this freedom is that many official APIs have more implementations than
the Sun's Reference implementation (RI).
The following is a partial list of Application Programming Interfaces (APIs) for the Java
Programming Language.

Official APIs
Java Platform, Standard Edition (Java SE)

Name

Acrony

Description and Version History

Java Advanced
Imaging

JAI

A set of interfaces that support a high-level programming


model allowing to manipulate images easily.

Java Data Objects

JDO

A specification of Java object persistence.

A full-featured, extensible help system that enables you to


incorporate online help in applets, components, applications,
operating systems, and devices.

JavaHelp

Java Media
Framework

JMF

An API that enables audio, video and other time-based media to


be added to Java applications and applets.

Java Naming and


Directory Interface

JNDI

An API for directory services.

Java Speech API

JSAPI

This API allows for speech synthesis and speech recognition.

Java 3D

J3D

A scene graph-based 3D API.

Java OpenGL

JOGL

A wrapper library for OpenGL.

Java USB for


Windows

(none)

A USB communication of Java applications

b) The standard was created to simplify the development of CORBA applications, while preserving all major
benefits. RMI-HOP is largely based on the Object by Value concept that serves as a container or direct
replacement for CORBA structures, unions, sequences, arrays and strings. The IDL is not used. Instead,
the data structure definitions supposed automatically, collecting the necessary data via reflection
mechanisms. When CORBA needs supplementary generated classes for each non trivial data structure
being transferred, RMI-HOP only uses the generated code for remote objects. Less generated code results
in the smaller footprint.

Both CORBA and RMI-IIOP use the same GIOP communication standard. If required, it is possible to
generate the IDL definitions for the involved RMI-IIOP data structures and use these definitions to arrange
the interoperability between the RMI-IIOP and plain CORBA applications.
The recent versions of RmMI-IIOP derive their servants from the standard Servant (CORBA) class. Hence
it is possible to connect them to the CORBA ORB manually, involving, if necessary, the Portable Object
Adapter, Portable Interceptors, CORBA naming service and all other standard CORBA features.
Hello world example (Java) for RMI & HOP: The standard name for Java RMI-HOP implementation
package is javax.rm.CORBA. The Interfaces
public interface MyServer extends Remote {
// The client passed self as the first parameter. The server can call
the
// remote method on the client. This is useful when the request processing takes //a lot of time.
void receiveRequest(MyClient client, Tring message) throws
Remote Exception; >
public interface MyClient extends Remote

// This remote method is called by the server.


void receiveRep!y(String message) throws RemoteException;
>
The client and server implementations, providing the functionality.
public class MyServerlmpI implements MyServer {
void receiveRequest(MyClient client, String message) throws
RemoteException {
System.out.println(The client says: +message);
client.receiveReply(Yes, l,+message+, + message+,
+message-f ); >
>

public class MyCleintlmpI implements Myclient {


MyServer server;
public MyClientlmpl(String ServerJOR, ORB orb) throws Exception
{
server = (MyServer)PortableRemoteObject.narrow( orb.string_to_object(Server_IOR), MyServer.class);
>
// This Is remote method.
void receiveReply(String message) throws RemoteException {
System.out.printlnCAnd the answer is: ~+message); >
// This is not a remote method, it is a local method.
public void talk(String conversation) {
server.receiveRequest(this, conversation);
>
>
The RMI-HOP developing tool, usually called rmic, will use the two classes above and will create two stubs
(for use on remote side) and the two ties (for use on the serving side}, one pair for the server and another
pair for the client.
The code, required to start the server
new ThreadQ {
public void run() <
try
// Create the CORBA ORB. MyServerlmpI.orb = ORB.init(args, properties); // Obtain the root Portable
Object Adapter; POA rootPOA = POAHelper.narrow (MyServerlmpl.orb.
resolve_initiaLreferences(RootPOA)); // MyServerlmpI contains the implementation of // the methods that
our server must support. MyServerlmpI impl = new My5erverlmpl{);
PortableRemoteObject.exportObject(impl); // Construct the tie that is also the Servant. // The
classMyServerlmpl_Tie is generated automatically from MyServerlmpI.
Tie tie = new_MyServer!mpl_Tie(); // Set the invocation target for this tie tie.setTarget(impl);

//Obta in the reference to the corresponding CORBA object org.omg.CORBA object =


rootPOA.servant_to_reference((Servant) ite); // Activate the root POA.
rootPOA.the_POAManager().activate(); // Get the IOR URL that must be passed to clients. String
Server_IOR = MyServerlmpI .orb.object_to_ string(object);
MyServerlmpi.crb.run{); // The content of the string variable Server_10R must be somehow transferred
// to our client. >
catch (Exception exc) {
exc.printStackTrace();
>
>
}.start();
The code, required to start the client
MyClient the_client;
new Thread() {
public void run() {
try
{
ORB orb ^.^.mimiiys, parameters); the_client = new MyClient!mpl(Server_IOR, orb);
POA rootPOA =
POAHelper.narrow(desk.orb.resolve_initial_referencesCRootPOA)); rootPOA.
the_POAManager().activate(); // Construct the tie. Tie tie = new_MyClientlmpLTie(); // Set the implementing
class (invocation target). tie.setTarget(the_client); // Connect the tie as POA servant.
org.omg.CORBA.Object object = rootPOA.servant_to_reference(Servant)tie);
// The value of the string IOR can be used to find this object on the web
String IOR = desk.orb.object_to_string(object); orb.run();
>
catch (Exception exc) {

exc. pri ntS tackTrace(); >


}
}.start();
Now, somewhere in the code, after the ORB thread has already started, we may call:
the_client.talkCit is raining);
Executing: The server (First) and the client (second) are started on the two different machines (or as a two
separate processes on the same machine).

Q5. a) What is package and how it is useful in programming?


b) Class is the heart of Every Java applet, Comment.

package is important because it's a standard way for people to


build Emacs extensions that can be incorporated by other Emacs users
quickly and easily. We no longer need to have a 3 or 4 year wait for a
new piece of code to get into Emacs.
Ans a)

By default Emacs pulls packages from a GNU package repository called


ELPA. ELPA has strict submission requirements, the ownership of the
code must still be assigned to the FSF. But it's easy to add usage of
other repositories to your Emacs, rather like you can with yum,
or apt ormacports.
A couple of other Emacs package repositories have sprung
up, marmalade-repo by Nathan Weizenbaum and now maintained by me
is a repository for Emacs packages that does not require code
ownership to be assigned to the FSF; indeed, it does not even require a
free licence (though that may change if I feel it's becomming an issue).
It's really easy to get your code into marmalade. You just register with
maramalade, build your package and upload it.
Another repository, called Melpa is rather clever in that it creates a
repository automatically out of code on GitHub. There's no need to
upload your code to Melpa, you just mark your repository in a particular
way for Melpa to pull it and build it for you.
b) A Java applet is a small application written in Java and delivered to users in the form
of bytecode. The user launches the Java applet from a web pageand it is then executed within
a Java Virtual Machine (JVM) in a process separate from the web browser itself. A Java applet

can appear in a frame of the web page, a new application window, Sun's AppletViewer or a
stand-alone tool for testing applets. Java applets were introduced in the first version of the Java
language in 1995.
Java applets can be written in any programming language that compiles to Java bytecode. They
are usually written in Java but other languages such asJython,[8] JRuby,
[9]
Scala or Eiffel (via SmartEiffel)[10] may be used as well.
Java applets run at very fast speeds comparable to, but generally slower than, other compiled
languages such as C++. Until approximately 2011 Java applets had been many times faster
than JavaScript.[11] Unlike JavaScript, Java applets have access to 3D hardware acceleration,
making them well suited for non-trivial, computation intensive visualizations. As browsers have
gained support for hardware accelerated graphics thanks to the canvastechnology (or
specifically WebGL in the case of 3D graphics), as well as just in time compiled JavaScript, the
speed difference has become less noticeable.
Since Java's bytecode is cross-platform (or platform independent), Java applets can be executed
by browsers (or other clients) for many platforms, including Microsoft
Windows, FreeBSD, Unix, OS X and Linux. It is also trivial to run a Java applet as an application
software with very little extra code so that it can be run directly from the integrated development
environment (IDE).

CASE STUDY-1
A spelling Checker: Many popular word processing software packages have built in spell checkers.
1. You are asked to develop your own spell-checker utility. We make suggestions to help get
youstarted. You should then consider adding more capabilities. Use a computerized dictionary
(if you have access to one) as a source of words.
Ans If the word is not present in the array, your program should print word is

not spelled correctly.


Then your program should try to locate other words in wordList that might be
the word the user intended to type. For example, you can try all possible single
transpositions of adjacent letters
to discover that the word default is a direct match to a word in wordList. Of
course, thiimplies that your program will check all other single transpositions,
such as edfault, dfeault,

CASE STUDY-2
2. Implement other tests such as replacing each double letter with a single letter and any other test
youcan develop to improve the value of your spell checker.
Ans f the word is not present in the file, your program should print "Word is not spelled correctly."

Then your program should try to locate other words in the file that might be the word the user
intended to type. For example, you can try all possible single transpositions of adjacent letters to
discover that the word "default" is a direct match to a word in the file. Of course, this implies that

your program will check all other single transpositions, such as "edfault," "dfeault," "deafult,"
"defalut" and "defautl." When you find a new word that matches one in the file, print that word in
a message such as "Did you mean "default?"."
Implement other tests, such as the replacing of each double letter with a single letter and any
other tests you can develop to improve the value of your spell checker.

Potrebbero piacerti anche