0 ratings0% found this document useful (0 votes) 2K views80 pagesObject Oriented Programming
5 th sem Makaut organizer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
OBJECT ORIENTED
PROGRAMMING
Introduction to Object-Oriented Programming
Features of Object Oriented Programming
Inheritance in OO Design
implementation of OO Language Features
Generic Types and Collections GUIS
NOTE:
MAKAUT course structure and syllabus of 5" semester has been changed from 2020.
The syllabus of this subject is restructured & reorganized with selected topics from
Previous OBJECT ORIENTED PROGRAMMING [CS 504D]. Few new topics are
introduced in present curriculum. Taking special care of this matter we are providing
Chapterwise relevant MAKAUT university solutions and some model questions &
answers for newly introduced topics along with the complete solutions of new
University papers, so that students can get an idea about university questions
Pattems.
12
48
62
77POPULAR PUBLICATIONS
INTRODUCTION TO OBJECT-ORIENTED
PROGRAMMING
Very Short Answer Type Questions
4. Which one of the following statements is wrong? [WBUT.2912, 2015;
a) A base class reference can refer to an object of a derived class,
b) The dynamic method dispatch is not carried out at the run time
c) The super() construct refers to the base class constructor
d) The super.base-class-method-name ( ) format can be used only within 2
derived class
Answer: (b)
2. Out of the following which one is not correctly matched? (WBUT 2012, 215
a) Int - 24 bits b) Short - 16 bits c) Double — 64 bits @) Byte — 2 bits
Answer: (a)
3. In which memory a String is stored, when we create 2 string using new
operator? {WBUT 2027]
Answer: Heap Memory
4. Out of the following which one is not correctly matched? [WBUT 2027)
a) JAVA — Object Oriented Language
b) FORTRAN — Object Oriented Language
c) C++ - Object Oriented Language
d) BASIC - Procedural Language
Answer: (c)
5. Consider the following 2 statements (S1 and S2). (WSUT 2027]
(S1) C++ uses compiler only
(S2) Java uses compiler and interpreter both
Above statements are true or false?
Answer: True
Short Answer estions
4. What do you mean by object-oriented programming? [WBUT 2004, 2007]
How is it different from conventional procedural/structural programming?
[WBUT 2004, 2005, 2007]
OR,
List out the differences between Procedure Oriented Programming and Object
Oriented programming. [WBUT 2017, 2022]
Oop-2* OBJECT ORI
nswer:
x type of programming in which programmers define not only the data type of a data
structure, but also the types of operations (functions) that can be applied to the data
structure. In this way, the data structure becomes an object that includes both data and
functions. In addition, programmers can create relationships between one object and
another. For example, objects can inherit characteristics from other objects.
To perform object-oriented programming, one needs an object-oriented programming
language (OOPL). Java, C++ and Smalltalk are three of the more popular languages, and
there are also object-oriented versions of Pascal.
PROCEDURAL LANGUAGE OBJECT ORIENTED LANGUAGE
i) More concerned with: the processing of | i) Concemed to develop an object or
|_procedures and functions. application based on real time.
ii) It is not applicable to procedural language. | ji) More emphasis is given on data rather
than procedures, while the programs are
divided into. Objects and the data is
encapsulated. (Hidden) from the external
environment, providing more Security to
data,
ili) Here itis strictly restricted.
iii) Here it is possible to expose Data and/or
variables to the extemal entities.
iv) There is no communication in procedural
language rather its simply a passing values to
the Arguments to the
Functions and / or procedures.
¥) Itfollows Top Down Approach to
Program Execution.
Vi) This type of programming uses traditional
way of calling functions and. returning
values.
iv) The Objects communicate with each
other via Functions.
¥) Itfollows Bottom Up Approach of
Program Execution.
vi) Object oriented concepts includes
Inheritance, Encapsulation and Data
Abstraction, Late Binding, Polymorphism,
Multithreading, and Message Passing
vii) Examples:
vil) Examples:
JAVA, VBNET, C#.NET
C, VB, Perl, Basic, FORTRAN.
2. What is the difference between Java and C++ in respect of language functions?
[WBUT 2014)
Answer: ’
Everything is an object in Java (Single root hierarchy as everything gets derived from
java.lang.Object).
Java does not have all the complicated aspects of C++ (For ex: Pointers, templates,
Unions, operator overloading, structures etc..). ;
There are no destructors in Java. (automatic garbage collection).
Java does not support conditional compile (Hifdef/#ifndef type).
ad support is built into java but not in C+
OoP-3POPULAR PUBLICATIONS
Java does not support default arguments. There’s no scope resolution operator :: in Jaya,
Java uses the dot for everything, but can get away with it since you can define elements
only within a class. Even the method definitions must always occur within a class, so
there is no need for scope resolution there either.
‘There’s no “goto” statement in Java.
Java doesn’t provide multiple inheritance (MI), at least not in the same sense that C++
does. Exception handling in Java is different because there are no destructors,
Java has method overloading, but no operator overloading. The String class does use the
+ and += operators to concatenate strings and String expressions use automatic type
conversion, but that’s a special built-in case.
Java is interpreted for the most part and hence platform independent.
3. What is an Abstract Data Type? How to implement an ADT? [MODEL QUESTION]
Answer:
An Abstract Data Type (ADT) is the specification of a data type within some
programming language, independent of an implementation. The interface for the ADT is
defined in terms of a type and a set of operations on that type. The behaviour of each
operation is determined by its inputs and outputs. An ADT does not specify how the data
type is implemented. A data structure is the implementation for an ADT. In an object-
oriented language like Java, an ADT and its implementation together make up a class.
Each operation associated with the ADT is implemented by a member, function or
method. The variables that define the space required by a data item are referred to as data
members. An object is an instance of a class, that is, something that is created and takes
up storage during the execution of a computer program.
The operations of an abstract data type are classified as follows:
1, . Creators create new objects of the type. A creator may take an object as an
argument, but not an object of the type being constructed.
2. Producers create new objects from old objects of the type. The concat method of
String, for example, is a producer. It takes two strings and produces a new one
representing their concatenation.
3. Observers take objects of the abstract type and return objects of a different type. The
size method of List, for example, returns an int.
4, Mutators change objects. The add method of List, for example, mutates a list by
adding an element to the end.
Implementation of ADT:
There can be different ways to implement an ADT. For example, the List ADT can be
implemented using arrays, or singly linked list or doubly linked list. Similarly, stack ADT
and Queue ADT can be implemented using arrays or linked lists.
In Stack ADT Implementation instead of data being stored in each node, the pointer to
data is stored. The program allocates memory for the data and address is passed to t
stack ADT. The head node and the data nodes are encapsulated in the ADT. The calling
OOP-4OBJECT ORIENTED PROGRAMMING
function can only see the pointer to the stack, The stack head structure also contains a
pointer to fop and count of number of entries currently in stack.
Pseudocode: .
This is asimple way of implementing the Stack ADT using an array. Here, elements are
added from left to right and a variable keeps track of the index of the top clement.
public class Stack (
private static final int CAPacrTy=10;
private int capacity;
private int top=-1;
private Object [] obj;
public Stack(int cap) (
capacity=cap;
obj=new Object [capacity];
}
public Stack() {
this (CAPACITY) ;
>
public int size()(
return .top+1;
}
public Object top(){
if(isEmpty())
return "Stack is empty.";
return obj[top];
d
public boolean isEmpty(){
return top<0;
d
public boolean isFull() {
return size()>=capacity;
}
public void push(Object 0) {
if(size()>=capacity) (
System.out.println("Stack is full.");
return;
)
obj[++top]=o;
public Object pop()(
if (isEmpty()) return "Stack is empty.
Object temp;
temp=obj [top] ;
obj [top--]=null;
return temp;
oop-5POPULAR PUBLICATIONS
4. Write the functions of the List ADT. [MODEL QUESTION,
Answer:
A list contains elements of the same type arranged in sequential order and following
opetaions can be performed on the list.
get() — Return an element from the list at any given position.
insert() — Insert an clement at any position of the list.
remove() - Remove the first occurrence of any clement from a non-empty list,
removeAt() — Remove the element at a specified location from a non-empty list,
replace() - Replace an element at any position by another clement.
size() - Retum the number of clements in the list.
isEmpty() — Return true if the list is empty, otherwise retuin false.
isFull() — Return true if the list is full, otherwise return false.
The List ADT Functions is given below:
Banas
ADT
Public Functions
[ create list ] | traverse [ retrieve Node desttoy list |
list count Empty list | ful fist |
remove Node
insert
Private Functions
OOP-65. What is Stack ADT? [MODEL QUESTION]
Answer:
In Stack ADT Implementation instead of data being stored in each node, the pointer to
data is stored. The program allocates memory for the data and address is passed to the
stack ADT. The head node and the data nodes are encapsulated in the ADT. The calling
function can only see the pointer to the stack. The stack head structure also contains a
pointer to fop and count of number of entries currently in stack.
‘8) Conceptual +b) Physical Structure
stack count stackMax
000
1) LF
‘A Stack contains clements of the same type arranged in sequential order. All operations
take place at a single end that is top of the stack and following operations can be
performed:
+ push()— Insert an element at one.end of the stack called top.
+ pop()~ Remove and return the element at the top of the stack, if itis not empty.
+ peek() — Return the element at the top of the stack without removing it, if the
stack is not empty.
+ size() - Return the number of elements in the stack.
+ isEmpty() — Return true if the stack is empty, otherwise return false.
+ isFull() —Return true if the stack is full, otherwise return.
6. What is Queue ADT? Explain its operations. [MODEL QUESTION]
Answer: .
The queue abstract data type (ADT) follows the basic design of the stack abstract data
type. Each node contains a void pointer to the data and the link pointer to the next
element in the queue, The’program’s responsibility is to allocate memory for storing the
data.
OOP-7POPULAR I IS
Pen) Ea i
1) Conceptual
Re
om 2 ow Fo Mow Boe oH
SS
) Physical Suucture
A Queue contains elements of the same type arranged in sequential order. Operations
take place at both ends, insertion is done at the end and deletion is done at the front.
Following operations can be performed:
* — enqueue()— Insert an element at the end of the queue.
« — dequeue() — Remove and return the first element of the queue, if the queue is not
empty.
« peek() - Return the element of the queue without removing it, if the queue is not
empty. +
* size() — Return the number of elements in the queue.
+ — isEmpty()— Return true if the queue is empty, otherwise return false.
* isFull()— Return true if the queue is full, otherwise return false.
7. Define: Abstraction function. [MODEL QUESTION]
Answer:
An abstraction functionmaps a state of the concrete machine to a state of
the abstract machine. It explains how to interpret each state of the concrete machine as 4
state of the abstract machine. It solves the problem of the concrete and abstract machines
having different sets of states.
1. An abstraction function that maps rep values to the abstract values they represent:
AF:ROA
OOP-8BIECT ORIENTED PROGRAMMIN\
‘The ares in the diagram show the abstraction function. In the terminology of functions,
the properties we discussed above can be expressed R A
by saying that the function is surjective (also
called onto), not necessarily bijective (also
called one-to-one), and often partial.
2. Arep invariantthat maps rep values to
booleans:
RI:R— boolean
For a rep value r, Ri(r) is true if and only if r is
mapped by AF. In other words, RI tells us whether
a given rep value is well-formed. Altematively, you can think of RI as-a set: it’s the
subset of rep values on which AF is defined.
8, Define: Concrete invariant. [MODEL QUESTION]
Answer:
An invariant is a property of a program that is always true, for every possible runtime
state of the program.
Long Answer estions
4, Write short note on Abstraction. [WBUT 2014, 2016, 2027]
Answer:
Abstraction is "To represent the essential feature without representing the back ground
details."
Abstraction lets us focus on what the object does instead of how it does it.
Abstraction provides us a generalized view of our classes or object by providing relevant
information.
Abstraction is the process of hiding the working style of an.object, and showing the
information of an object in understandable manner.
Real world Example of Abstraction:
Suppose we have an object Mobile Phone.
Suppose we have 3 mobile phones as following:
Nokia 1400 (Features:- Calling, SMS)
Nokia 2700 (Features:- Calling, SMS, FM Radio, MP3, Camera) :
Black Berry (Features:-Calling, SMS, FM Radio, MP3, Camera, Video Recording,
Reading E-mails) en wate
Abstract information (Necessary and Common Information) for the object "Mobile
Phone" is make a call to any number and can send SMS." |
So that, for mobile phone object we will have abstract class like following:
apsteebe class MobilePhone :
Public void Calling();
welts void SendSMs();
oor-9BLI
public class Nokiai400 : NobilePhone
{
}
public class Nokia2700 : YobilePhone
{
public void FMRadio();
public void MP3();
public void Camera();
}
public class BlackBerry : MobilePhone
c
public void FMRadio();
public void MP3();
public void Camera();
public void Recording();
public void ReadAndSendEmails();
}
‘Abstraction means putting all the variables and methods in a class which are necessary.
For example: Abstract class and abstract method.
Abstraction is the common thing.
example:
If somebody in our collage tell us to fill application form, we will fill our details like
name, address, data of birth, which semester, percentage you have got etc.
If some doctor gives us an application to fill the details, we will fill the details like name,
address, date of birth, blood group, height and weight.
So, in the above example what is the common thing?
Age, name, address so you can create the class which-consist of common thing that is
called abstract class.
That class is not complete and it can inherit by other class.
2. Write short note on Abstract data types and their specifications.
[MODEL QUESTION]
Answer:
An Abstract Data Type (ADT) is the specification of a data type within some
programming language, independent of an implementation. The interface for the ADT is
defined in terms of a type and a set of operations on that type. The behaviour of each
operation is determined by its inputs and outputs. An ADT does not specify how the data
type is implemented. These implementation details are hidden ftom the user of the ADT
and protected from outside access, a concept referred to as Encapsulation.
A data structure is the implementation for an ADT. In an object-oriented language like
Java, an ADT and its implementation together make up a class. Each operation associat
with the ADT is implemented by a member, function or method, The variables that define
the space required by a data item are referred to as data members, An object is #
instance of a class, that is, something that is created and takes up storage during
execution of a computer program.
OOP-10Abstract data Types are three types.
1, List ADT
2. Stack ADT
3. Queue ADT. 3
1. List ADT:
The data is generally stored in key sequence in a list which has a head structure
consisting of count, pointers and address of compare function needed to compare the data
in the list. The data node contains the pointer to a data structure and a self-referential
pointer which points to the next node in the list.
Compare
function NODE NODE NODE
ha Lp tone nooe
2. Stack ADT:
In Stack ADT Implementation instead of data being stored.in each node, the pointer to
data is stored. The program allocates memory for the data and address is passed to the
stack ADT. The head node and the data nodes are encapsulated in the ADT. The calling
function can only see the pointer to the stack. The stack head structure also contains a
Pointer to top and count of number of entries currently in stack. .
3. Queue ADT ne
The queue abstract data type (ADT) follows the basic design of the stack abstract data
type, Each node contains a void pointer to the data and the link pointer to the next
Clement in the queue. The program’s responsibility is'to allocate memory for storing the
data,
OoP-11OPULAR PUBLICATIONS
FEATURES OF OBJECT ORIENTED
PROGRAMMING
Very Short Answer Type Questions
4. All classes in Java are the sub-class of DWBUT 2007, 2049)
a) Final class b) Object class c) Static class d) Super class
Answer: (b)
2. In which class is the wait () method defined? [WBUT 2007, 2018)
a) Applet b) Runnable c) Thread d) Object
Answer: (d)
3. What is the correct ordering for the import, class and package declarations
when found in a single file? [WBUT 2010, 2012, 2015)
a) package, import, class b) class, import, package
c) import, package, class d) package, class, import
Answer: (a)
4. Asub-class having more than one super class is called [WBUT 2012]
a) category b) Classification c) Combination _d) Partial participation
Answer: (a)
5. Which one of the following statements is not correct? [WBUT 2012]
a) An interface can inherit another interface
b) The package name and subdirectory name need not be identical
c) Only the classes declared as public in a package are accessible outside that
package
d) The import java.awt.*; directive will not import classes in java.awt.event
. package
Answer: (d)
6. If a data-item is declared as a protected access specifier then it can be accessed
[WBUT 2012]
a) anywhere in the program b) by the base and derived classes
c) only by base classes d) only by derived classes
Answer: (b)
7. What is the output of this code fragment? [WBUT 2012, 2015]
4. int x= 3; int y= 10;
2. System.out.printin (y% x);
ajo b)1 c)2 d)3
Answer: (b)
OOP-12OBI ORIENTED PROGI IG
g. Which three form part of correct array declarations? [WBUT 2013]
. public int a []
static int []a
public [Jinta
private int a [3]
private int [3] a]
. public final int [] a
a)1,3,4 b) 2,4,5 °)1,2,6 d) 2,5, 6
Answer: (c)
Parry
9, Which cause a compiler error? [WBUT 2013]
a) int [] scores = (3, 5, 7};
b) int [] [] scores = (2, 7, 6}, (9, 3, 45};
¢) String cats [] = {“Fluffy", “Spot”, “Zeus”};
d) boolean results [] = new Boolean [] {true, false, true};
¢) Integer results [ ] = {new Integer (3), new Integer (5), new Integer (8)};
Answer: (b)
40. Which two cause a compiler error? [WBUT 2013]
1. float [] f = new float (3);
2. float f2[] = new float [];
3. float []f = new float [3];
4. -float £3 [] = new float [3];
5. float f5[]={1.0f, 2.0f, 2.09; .
a)2,4 b) 3,5 0) 4,5 d)1,2
Answer: (d)
11. public class Test { }
What is the prototype of the default constructor? [WBUT 2013]
a) Test () b) Test (void) c) public Test () d) public Test (void)
Answer: (c)
12. What is the most restrictive access modifier that will allow members of one
class to have access to members of another class in the same package?
a) public b) abstract c) protected [WBUT 2013]
d) synchronized _e) default access
Answer: (¢)
43. You want a class to have access to members of another class in the same
package. Which is the most restrictive access that accomplishes this objective?
a) public b) private [WBUT 2013]
¢) protected d) default access
Answer: (d)
[WBUT 2014]
14, Byte code of javais
a) platform dependent
c) no specific rule
Answer: (b)
b) platform independent
d) depend upon OS
OoP-13POPULAR PUBLICATIONS
15. Java virtual machine is
2) platform dependent totally b) independent
c) depends on machine architecture only d) depends on OS only
Answer: (c) '
[WBUT 2014, 2016)
16. Java is robust because [WBUT 2014)
a) it is object oriented b) garbage collection is present
c) platform independent d) exception handling
Answer: (d)
17. Constructor can be overloaded [WBUT 2014, 2015}
a) never b) always c) partially 4) either (b) or (c)
Answer: (b)
18. Which of the following cannot be used for a variable name is Java?
[WBUT 2046]
2) Identifier . b) Keyword
c) Identifier & Keyword d) None of these
Answer: (b)
19. What is the range of the char typo? [WBUT 2016]
a) 0 to 2 b) 0 to 2° c) 0to 2-4 d)0to 2-4
Answer: (2)
20. The import statement is always [WBUT 2016)
a) the first non-comment statement in a java program file
b) the default non-comment statement in java program file
c) 2 non-comment statement and can be defined anywhere in the program
d) none of these
Answer: (a)
21. Which of the following values can a Boolean variable contain? = [WBUT 2016]
a) True & False b)O&4
c) Any integer value d) True
Answer: (a)
22. What is the output of this program? [WBUT 2016)
class area {
public static void main (String args{])
{
double r, pi, ar
2=9.8;
piz3.14)
a=pitrtr;
System.out .printin(a);
y
,
a) 301.5656 b) 301 c) 301.56 0
tame ) d) 301.5656000!
OOP-14OBJECT ORIENTED PROGRAMMING
93. How many public class can be allowed in Java? {WBUT 2017]
a) One b) Two c) Many 4d) None of these
“Answer: (a)
24. Whether Java need compiler or interpreter [WBUT 2017]
a) compiler b) interpreter
c) both (a) and (b) d) none of these
‘Answer: (c)
25, Does any Java program contains more than one main method? [WBUT 2017]
a) Yes ee b) No
c) Sometimes it is possible d) In different package
Answer: (a) '
26. AWT package is uses for [WBUT 2017]
a) Component and graphics b) Component
¢)Graphics d) None of these
Answer: (a)
27. What is bytecode in context of Java? ; [WBUT 2018]
a) The type of code generated by a Java compiler
b) The type of code generated by Java Virtual Machine
c) It is another name for a Java Source file
4) It is the code written within the instance methods of a class
Answer: (b)
28. Which of the following statements regarding static methods are correct?
[WBUT 2018]
a) Static methods are difficult to maintain, because you cannot change their
implementation
b) Static methods can be called using an object reference to an object of the
class in which this method is defined
c) Static methods are always public, because they are defined at class-level
d) Static methods do not have direct access to non-static methods which are
defined inside the same class
Answer: (b)
29, Given the flowing piece of code [WBUT 2018]
public class C(
Public abstract double calc_sa( )7
}
Which of the following statements is true?
a) The keywords public and abstract cannot be used together
b) The method calc_sal() in class C must have a body
c) Must add a return statement in method calc_sal()
d) Class C must be defined abstract
Answer: (d)
OOP-15POPULAR PUBLICATIONS
30. A subclass is placed in a different package than the super class. In order to
allow the subclass access a method defined in uper class, identify the correct
access specifiers(s) [WBUT 2018)
a) protected b) public ¢) private d) default
Answer: (c)
34. Which of the following keywords are used to control access to a class
member? [WBUT 2022]
a) New b) Abstract ¢) Public 4d) Interface
Answer: (b & c)
32. An abstract class, which declared with the “abstract” keyword, cannot be
instantiated. True or False?
Answer: True
[WBUT 2022]
33. “A package is a collection of classes, interfaces and sub-packages” — The
above statement is true or false?
Answer: True
34, Which of the following statements is valid array declaration?
a) int number () —_b) float average []
Answer: (b)
35. Java is robust because
a) it is object oriented
c) inheritance is present
Answer: (b & d)
[WBUT 2027]
[WBUT 2027]
¢) int marks 4d) count int g
[WBUT 2022]
b) garbage collection is present
d) exception handling
Short Answer Type Questions
1. Differentiate between association and aggregation.
[WBUT 2006, 2007, 2018]
Answer:
ASSOCIATION AGGREGATION
i) association is a relationship between two | i) Aggregation. is a special case of
objects. sociation,
ii) association defines the multiplicity A directional association between
between objects. for example one-to-one,
‘one-to-many, many-to-one, many-to-many
all these’ words define an association
between objects
relationship.
objects. When an object *has-a’ - another
object, then you have got an aggregation
between them. Direction between them
specified which object contains the other
object. Aggregation is also called a “Has-a”
Detioted by,
———-
Denoted by,
——>
OOP-16OBJECT ORIENTED PROGRAMMING
ASSOCIATION a AGGREGATION
a )
subscribes 0. Ls Class
[_Pretsx |
subscriber * Subscribed magazin FistOrStudens tt [>
Class diagram example of association | Class diagram showing Aggregation between
between two class two classes
2. Explain various access modifiers (public, protected, private, default) in a class
definition, [WBUT 2006]
‘ OR,
What is the difference between default access specifier and public access
specifier?
Explain the differences between the ‘private’ and ‘protected’ access specifier in
java. [WBUT 2013]
OR,
Differentiate between protected and friendly access spe:
Answer:
One of the techniques in object-oriented programming is encapsulation. It concerns the
hiding of data in a class and making this class available only through methods. In this
way the chance of making accidental mistakes in changing values is minimized. Java
allows you to control access to classes, methods, and fields via so-called access
specifiers.
Java offers four access specifiers, listed below in decreasing accessibility:
© public
* protected
¢ default (no specifier)
* private
We look at these access specifiers in more detail.
public
Public classes, methods, and fields can be accessed from everywhere. The only
constraint is that a file with Java source code can only contain one public class whose
name must also match with the filename. If it exists, this public class represents the
application or the applet, in which case the public keyword is necessary to enable your
Web browser or appletviewer to show the applet. You use public classes, methods, or
fields only if yow explicitly want to offer access to these entities and if this access cannot
do any harm. An example of a square determined by the position of its upper-left comer
and its size:
Public class Square { // public class :
public x, y, size; // public instance variables
[WBUT 2018]
* OOP-17POPULAR PUBLICATIONS
Protected
protected methods and fields can only be accessed within the same class to Which the
methods and fields belong, within its subclasses, and within classes of the same package
but not from anywhere else. You use the protected access level when it is appropriate
for a class's subclasses to have access to the method or field, but not for unrelated classes,
default (no specifier)
If you do not set access to specific level, then such a class, method, or field will be
accessible from inside the same package to which the class, method, or field belongs, but
not from outside this package. This access-level is convenient if you are creating
packages. For example, a geometry package that contains Square and Tiling classes,
may be easier and cleaner to implement if the coordinates of the upper-left corner of
aSquare are directly available to the Tiling class but not outside the geometry
package.
private
private methods and fields can only be accessed within the same class to which the
methods and fields belong. private methods and fields are not visible within subclasses
and are not inherited by subclasses. So, the private access specifier is opposite to
the public access specifier. It is mostly used for encapsulation: data are hidden within
the class and accessor methods are provided. An example, in which the position of the
upper-left comer of a square can be set or obtained by accessor methods, but individual
coordinates are not accessible to the user,
public class square { // public class
private double x, y | // private (encapsulated) instance
variables
public setCorner(int x, int y) { // setting values of private
fields :
this.x
this.y
}
public getCorner(){ // setting values of private fields
return Point(x, yl;
}
7.
xt
yi
Summary of Access Specifiers
The following table summarizes the access level permitted by each specifier,
Situation public protected | defautt
Accessible to class
from same package?
unless
subclassQDIECT ORIENTED PROGRAMMING
Note the difference between the default access which is in fact more restricted than
the protected access. Without access specifier (the default choice), methods and
variables are accessible only within the class that defines them and within classes that are
part of the same package. They are not visible to subclasses unless these are in the same
kage. protected methods and variables are visible to subclasses regardless of which
package they are in.
4, State the Difference between the following:
static and final keyword [WBUT 2009, 2010, 2018]
Answer:
‘A final class cannot be extended. This is done for reasons of security and efficiency. A
final method cannot be overridden by subclasses, ‘
A final variable can only be initialized once, either via an initializer or an assignment
statement.
The "final" keyword is useful when applied to variables whose values will not change
during the lifetime of the program. If you've got constant values in your program which
will not change throughout, it is useful to declare them as final.
The keyword “static” when applied to a variable OR a method means that the variable or
method can be accessed without creating an instance ofthe class,
For examples of static variables see the Color class in the Java API. It uses static
variables such as BLACK, BLUE, PINK ete.
‘They can be referenced like:
Code:
useColor (Color. BLACK) ; ‘
instead of
Code:
Color myColorBlack = new Color();
useColor (myColorBlack. BLACK) ;
static can be used for methods for much the same effect.
When "final" is applied to @ class, the principle effect is that the class cannot be inherited
from. For example, the following would throw an error:
Code: ,
Public final class Dog {
pbs Dog() {
)
Public class JackRussell extends Dog (
yes JackRussell() (
)
ooP-19POPULAR PUBLICATIONS
4. Differentiate between Early binding and late binding. [WBUT 2010, 2018)
ol
R,
Whats the difference between static binding and dynamic binding? [WBUT 2011)
Answer:
Late Binding:
“e At run time, when it is known what class objects are under consideration, the
appropriate version of function is invoked. Since the function is linked with a
particular class much later after the compilation, this process is known as late
binding. It is also known as dynamic binding because the selection of the
appropriate function is done at run time dynamically. Dynamic binding requires
use of pointers to objects.
Late binding is implemented when it is not known which fiunction will be called,
though early binding is faster than late binding,
Early Binding:
* The overloaded member functions ate selected for invoking by matching
arguments. The compiler knows this information at the compile time and,
therefore, compiler is able to select appropriate function for a particular call at
compile time itself. This is called early binding or static binding or static
linking. This is also known as compile time polymorphism
Early binding determines execution path at compilation and late binding allows
for dynamic execution at runtime.
for example: In a native Win32 code environment (i.¢., non .NET), late binding
could refer to the use of a DLL library vs. the use of a static library - all the
references in a static library can be determined at compile time, but the
references in a DLL (dynamic link library) are not determined later until run
time.
5. What are the main characteristics of OOP Language? Explain each. [WBUT 2012]
Answer:
Encapsulation:
In programming, it is the process of combining elements to create a new entity. For
example, a procedure is.a type of encapsulation because it combines a series of computer
instructions. Likewise, a complex data type, such as arecordor class, relies on
encapsulation. Object-oriented programming languages rely heavily on encapsulation.to
create high-level objects. Encapsulation is closely related to abstraction and information
hiding.
Customer, waiter and kitchen are three shielded objects in the ‘cup of coffee’ example.
Customer and kitchen do not know each other. The waiter is the intermediary between
those two. Objects can't see each other in an Object Oriented world. The ‘hatch’ enables
them to communicate and exchange coffee and money.
Encapsulation keeps computer systems flexible. The business process can change easily.
The customer does not care about the coffee brew process. Even the waiter does not care.
This allows the kitchen to be reconstructed, is only the ‘hatch' remains the same. It is even
OOP-20OBJECT ORIENTED PROGRAMMING
ible to change the entire business process, Suppose the waiter will brew coffee
himself. The customer won't notice any difference,
Encapsulation enables OO experts to build flexible systems. Systems that can extend as:
your business extends. Every module of the system can change independantly, no impact
to the other modules.
Polymorphism:
In object-oriented programming, polymorphism (from the Greek meaning. "having
multiple forms") is the characteristic of being able to assign a different meaning or usage
to something in different contexts - specifically, to allow an entity such asa variable,
a function, or an object to have more than one form. There are several different kinds of
polymorphism. ,
1) A variable with a given name may be allowed to have different forms and the program
can determine which form of the variable to use at the time of execution. For example, a
variable named USERID may be capable of being cither an integer (whole number) or a
string of characters (perhaps because the programmer wants to allow a user to enter a
user ID as cither an employee number - an integer - or with a name - a string of
characters), By giving the program a way to distinguish which form is being handled in
cach case, either kind can be recognized and handled.
2) A named function can also vary depending on the parameters it is given. For example,
if given a variable that is an integer, the function chosen would be to seek a match against
a list of employee numbers; if the variable were a string, it would seek a match against a
list of names. In either case, both functions would be known in the program by the same
name. This type of polymorphism is sometimes known as overloading.
You drive an automobile, which has properties like wheel size, engine size, gas tank size,
and other properties. The automobile you drive is a concrete implementation of
the automobile interface. It has additional features, like sliding doors, logo type, cd
changer slot count, moon roof lever location, or other various properties that are specific
to the make/model of the car. In addition, automobile may have certain behaviors like
open/close door, open trunk, tum wheel, and other behaviors that would be specific to an
automobile.
In OO programming, using the automobile example, Automobile would be the base class,
and each automobile manufacturer would have its own implementation. For ingtance,
Honda has V-Tec technology, which is in its own implementation. Volvo uses! di
engines, which is the TDI technology. More importantly, you may add an added Igvel of
detail between automobile and the make/model implementation, such as Car, Trick, or
Suv super types, to provide more relevant information. peel
(
Inheritance: . i .
Different kinds of objects often have a certain amount in common with each other.
Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics
of bicycles (current speed, current pedal cadence, current gear). Yet each also defines
additional features that make them different: tandem bicycles have two seats and two sets
oop-21 4POPULAR PUBLICATIONS
of handlebars; road bikes have drop handlebars; some mountain bikes have an additionay
chain ring, giving them a lower gear ratio.
Object-oriented programming allows classes to inherit commonly used state and behavior
‘from other classes. In this example, Bicycle now becomes the superclass of
MountainBike, RoadBike, and TandemBike. ‘In the Java programming language, cach
class is allowed to have one direct superclass, and each superclass has the potential for an
unlimited number of subclasses:
Bicycle
A hierarchy of bicycle classes.
The syntax for creating a subclass is simple. At the Meaning of your class declaration,
use the extends keyword, followed by the name of the class to inherit from:
class MountainBike extends Bicycle (
// new fields and methods defining a mountain bike would go
here
}
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code
sto focus exclusively on the features that make it unique. This makes code for your
subclasses easy to read. However, you must take care to properly document the state and
behavior that each superclass defines, since that code will not appear in'the source file of
each subclass.
6. What do you meant by ‘Dynamic Method Dispatch’? [WBUT 2013]
Answer:
Refer to Question No. 8(a) of Long Answer Type Questions.
7. What is message passing? [WBUT 2018]
Answer:
Massage passing is a form of communication used in object-oriented programming as
well as parallel programming : Massage passing in Java is like sending an object i.e.
massages from one thread to another thread. It is used when threads do not have shared
memory and are unable to share variables to communicate,
OOP-22
«‘Thread 2
(Consumer)
Blocking Queue
OTT
As a example,
The producer and Consumer are the Threads. The producer will produce and consumer
will consume only. We use Queue to implement communication between thread.
8. Write a Java program to show use of abstract class and Interface. [WBUT 2018]
Answer:
A Java Program to show use of abstract class and Interface:
interface MyInterface ‘
¢
public void method ();
public void method2 ();
}
class Demo implements MyInterface
{
public void methodi ();
t 4
System.out.println ("implementation of methodl");
)
public void method2 ();
(
System.out.printin (“implementation of method2*);
)
Public static void main (String args{ 1)
{
MyInterface obj = newDemo ();
Obj .methodl () ;
d
)
9, What is qualified association? Describe with an example. [WBUT 2022]
Answer:
A qualifier may be used in an association; it distinguishes the set of objects at the far end
of the association based on the qualifier value. An association with a qualifier is
aqutlified association. Depicting a qualifier in a domain model communicates how, in
the domain, things of one class are distinguished in relation to another class.
OOP-23& UBLICATIONS
Example Qualified Association: Canvas & Figure
Canvas Figure id
10. What is an object? Why Java Is called an object oriented language?
[WBUT 2023)
Answer:
1" pa
Refer to Question No. 12 of Short Answer Type Questions.
2™ part: .
Java Language is considered an object-oriented language because it is based on the
concept of objects and classes. Without thé creation of objects and classes, it is
impossible to write any code in Java. Java supports the concepts of OOPS - Inheritance,
Data abstraction, polymorphism, and data encapsulation.
41. Explain static keyword with suitable Java code. [WBUT 2022]
Answer:
The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs
to the class than an instance of the class,
The static can be:
1. Variable (also known as a class variable)
2. Method (also known asa class method)
3. Block
4. Nested class
Use the static variable for the property that is common to all objects. For example, in
class Student, all students share the same college name. Use static methods for
changing static variables.
Consider the following java program, that illustrates the use of static keywords with
variables and methods.
class Student (
String name;
int rollNo;
//. static variable
static String cllgName;
/( static counter to set unique roll no
static int counter = 0;
public Student (string name)
this.name = name;
OOP-24}
this.rol1No = setRol1No();
}
// getting unique rol1lNo
MW through static variable (counter)
static int setRollNo()
{
counter++;
return counter}
y
// static method
static void setCllg(String name) ( cllgName = name; }
// instance method
void getStudentInfo()
i
system.out.printIn(*name : " + this.name);
System.out.println("rollNo : * + this.rol1No);
// accessing static variable
System.out.println("cllgName : " + cllgName);
}
// Driver class
public class StaticDemo {
}
public static void main(String[]. args)
{
// calling static method
// without instantiating Student class
student.setCl1g("X¥Z");
Student s1 = new Student("Alice");
Student s2 = new Student(*Bob");
s1.getStudentinfo();
s2.getStudentInfo();
Output
name : Alice
TolINo : 1
ellgName : XYZ
name : Bob
tolINo: 2
cligName : XYZ
42. Write down the features of Object oriented Programming. [MODEL QUESTION]
OOP-25POPULAR PUBLICATIONS
Answer:
Features of OOPs:
1, Classes
. Objects
. Data Abstraction
Encapsulation
Inheritance
Polymorphism
ayer
1. Class: Class represents a real world entity which acts as a blueprint for all the objects,
We can create as many objects as we need using Class.
Example:
We create a class for “ Student ” entity as below
Student. java
Class Student {
String id;
int age;
String course;
void enroll (){
System.out.println(*Student enrolled");
} .
3
Above definition of class contains 3 fields id,age and course and also it contains behavior
or a method called “ enroll ”.
2. Objects: Object Oriented Programming system(OOPS) is designed based on the
concept of “Object”. It contains both variables (used for holding the data) and methods
(used for defining the behaviors). We can create any number of objects using this class
arid all those objects will get the same fields and behavior.
Student s1 = new Student();
Now we have created 3 objects s1,s2 and s3 for the same class “ Student ”. We can create
as many objects as required in the same way.
We can set the value for each field of an object as below,
s1.id=123;
s2.age=18;
s3.course="computers”;
3. Data Abstraction:
Abstraction is a process where you show only “relevant” data and “hide” unnecessary
details ofan object from the user.
For example, when you login to your bank account online, you enter your user_id.and
password and press login, what happens when you press login, how the input data sent to
server, how it gets verified is all abstracted away from the you.
OOP-26OBJECT ORIENTED PROGRAMMING
We can achieve “ abstraction ” in Java using 2 ways
a. Abstract class
b. Interface
a. Abstract Class
«Abstract class in Java can be created using “ abstract” keyword
+ If we make any class as abstract then it can't be instantiated which means we are
not able to create the object of abstract class.
* Inside Abstract class, we can declare abstract methods as well as concrete
methods.
« So using abstract class, we can achieve 0 to 100 % abstraction.
Example:
Abstract class Phone(
void receiveCall();
Abstract void sendMessage() ;
}
Anyone who. needs to access this functionality has to call the method using the Phone
object pointing to its subclass.
b. Interface
* Interface is used to achieve pure or complete absiraction.
« We will have all the methods declared inside Interface as abstract only.
« So, we call interface as 100% abstraction.
Example: a
‘We can define interface for Car functionality abstraction as below
Interface Car{
public void changeGear( int géarNumber) ;
public void applyBrakes() ;
)
Now these functionalities like changing a gear and applying brake are abstracted using
this interface.
4, Encapsulation:
+ Encapsulation is the process of binding object state (fields) and behaviors
(methods) together in a single entity called “Class”.
+ Since it wraps both fields and methods in a class, it will be secured from the
outside access.
«© We can restrict the access to the members of a class using access modifiers such
as private,protected and public keywords.
© When we create a class in Java, it means we are doing encapsulation.
+ Encapsulation helps'us to achieve the re-usability of code without compromising
the security.
Example:
class EmployeeCount 7
private int numOfEmployees = 0/
OOP-27LAR PUBLICATIONS
public void setNoOfEmployees (int count)
wpeegattscs = count;
Spite double getNoOfEmployees ()
aie numOfEmployees;
,
}
public class EncapsulationExample
public static void main(String args{])
{
EmployeeCount obj = new EmployeeCount ();
obj . setNoOfEmployees (5613) ;
System.out.println("No Of Employees:
*+(int)obj.getNoofEmployees () );
}
}
5. Inheritance:
© One class inherits or acquires the properties of another class.
Inheritance provides the idea of reusability of code and each sub class defines only
those features that are unique to it, rest of the features can be inherited from the
parent class.
1. Inheritance is a process of defining a new class based on an existing class by
extending its common data members and methods.
2. Itallows us to reuse of code, it improves reusability in your java application.
3. The parent class is called the base class or super class. The child class. that
extends the base class is called the derived class or sub class or child class.
To inherit’ a class we use extends keyword. Here class A is child class and class B is
parent class.
class A extends B
{
i
6. Polymorphism:
* _ It is the concept where an object behaves differently in different situations.
* Since the object takes multiple forms, it is called Polymorphism.
+ _Injaya, we can achieve it using method overloading and method overriding,
© There are 2 types of Polymorphism available in Java,
4
Method overloading
In this case, which method to call will be decided at the compile time itself based on
number or type of the parameters, Static/Compile Time polymorphism is an example for
method overloading. i
Oop.28 ! 'OBJECT ORIENTED PROGRAMMING
Method overriding
In this case, which method to call will be decided at the run time time based on what
object is actually pointed by the reference variable,
4.a) Explain role name in an association with example. [WBUT 2004]
Discuss association. zi [WBUT 2013}
b) What is aggregation? How aggregation is different from association and
generali ization? [WBUT 2004]
: OR,
Discuss aggregation. [WBUT 2013]
Answer:
a) An association implies two model elements have a relationship - usually implemented
as an instance variable in one class. This connector may include named roles at each end,
cardinality, direction and constraints. Association is the general relationship type between
elements. For more than two elements, a diamond representation toolbox element can be
used as well. When code is generated for class diagrams, named association ends become
instance variables in the target class. So, for the example below, "playsFor" will become
an instance variable in the "Player" class.
Player
+plays For
1 O28
An association end role is a specialization of an association end, used to describe an
association end's behavior in a particular context.
In the UML metamodel AssociationEndRole is a sub-class of AssociationEnd.
Two or more association end roles are associated with each association role.
Classes can also contain references to each other. The Company class has two attributes
that reference the Client class.
-name : String
-contactPerson:Client
employees: Client{]
Although this is perfectly correct, it is sometimes more expressive to show the attributes
aS associations.
OOP-29POPULAR PUBLICATIONS
Per i
Coat 'erson 1 Gian
-lastName : String
name : String Asie Sing
“emai
1
The above two associations have the same meaning as the attributes in the old version of
the Contact class,
The first association (the top one) represents the old contactPerson attribute. There is
‘one contact person in a single Company, The multiplicity of the association is one to one
meaning’ that for ‘every Companythere is one and only one conttactPerson and for
each contactPerson there is one Company. In the bottom association there are zero or
many employees for each company. Multiplicities can be anything you specify. Some
examples are shown:
0 Zero
1 One
Ls one or many
1.2, 10..* one, two or ten and above but not three through nine
The arrows at the end of the associations represent their navigability. In the above
examples, the Company references Clients, but the Client class does not have any
knowledge of the Company. You can set the navigability on either, neither or both ends
of your associations. If there is no navigability shown then the navigability is unspecified.
b) Difference between Association and Aggregation:
Refer to Question No. 1 of Short Answer Type Questions.
Difference between Aggregation and Generalization:
AGGREGATION GENERALIZATION
i) A directional association between objects, | i) Generalization uses a “is-a” relationship
When an object ‘has-a’ another object, then | from a specialization to the generalization
you have got an aggregation between them class. Common structure and behavior are
used from the specialization to the
generalized class. At a very broader level we
can understand this as inheritance.
ii) Denotes by, ii) Denotes by,
er
Ti) It means for example one College is build | iii) Consider there exists a class named
up of Departments and again departments | Person. A student is a person. A faculty is a
contains classes right here school is | person, Therefore here the relationship
aggregation of departments and again | between student and person, similarly. faculty
department is aggregation of classes, here you | and person is generalization.
can perfect aggregation of things if you delete
the main object called school all associated
departments and classes will get delete.
OOP-302. What are the differences between ‘abstract c! and ‘interface’?
[WBUT 2005, 2007, 2009, 2010, 2011, 2013, 2018, 2022]
Answers
‘Abstract class Interface
1. | An abstract class can contain | An interface can have only abstract methods,
implementation of some methods’ apart
from the abstract methods, This makes
abstract class to make a redd only class,
7, | A class that extends or inherits an abstract | A” class that Implements or inherits an
class must reside in the same class | interface need not be in the same hierarchy in
hierarchy where the parent abstract class | which the interface belongs.
belongs.
‘A new abstract class cannot be fitted easily | Multiple classes can implement a new
into a class hierarchy. For example if two | interface, as it is not a mandate that these
classes inherits or extends the same new | classes will be in the same hierarchy in which
abstract class, then the abstract class needs | the interface belongs,
to be placed higher up in the hierarchy
above these two classes. This can disturb
the class hierarchy, as this will force all the
descendants to extend the new abstract
class. This may involve some extra
implementation overhead for _ these
descendants.
4. | A class can at most extend or inherit one] A class can implement multiple interfaces
single ‘parent. This is known as single | and at the same time can extend a class for
directional inheritance. any concrete implementation,
This mixed type of inheritance helps us to
design more flexible data structures. This is
known as multi-directional inheritance.
3. What do you mean by parameter passing? What is call by value and call by
reference? Write down two programs to define call by value and call by reference.
[WBUT 2014]
OR,
a) What do you mean by parameter passing?
b) What is the difference between call by value or pass by value and call by
teference or pass by reference? Explain. [WBUT 2015]
Answe :
1" Part: ‘
Parameter passing is the mechanism used to pass parameters to a procedure (subroutine)
or function. The most common methods are to pass the value of the actual parameter (call
by value), or to pass the address of the memory location where the actual parameter is
stored (call by reference), The latter method allows the procedure to change the value of
the parameter, whereas the former method guarantees that the procedure will not change
the value of the parameter. Other more complicated parameter-passing methods have
n devised, notably call by name in Algol 60, where the actual parameter is re-
Cvaluated each time it is required during execution of the procedure,
oop-31