Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
130 views
oops 5th sem 2024 organizer
Object Oriented Programming Organizer 2024
Uploaded by
roymegha0311
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
Download now
Download
Save oops 5th sem 2024 organizer For Later
Download
Save
Save oops 5th sem 2024 organizer For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
130 views
oops 5th sem 2024 organizer
Object Oriented Programming Organizer 2024
Uploaded by
roymegha0311
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
Download now
Download
Save oops 5th sem 2024 organizer For Later
Carousel Previous
Carousel Next
Save
Save oops 5th sem 2024 organizer For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 83
Search
Fullscreen
| ai https J/www.instagram.com/ranjan_mahato_rkm/ _ PROGRAMMING Introduction to Object-Oriented Programming... fil Features'of Object Oriented Programming sel ; 12 | Inheritance in OO Design sugal | Implementation of 00 Language Features t : 65 | Generic Types and Collections GUIS " : 81 | . w | | { NOTE:»): MAKAUT course structure and syllabus of 5" semester has béen changed from 2020. The syllabus of this subject is restructured & reorganized with selected topies 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 fot newly introduced topics along’ with the ‘complete ‘solutions’ of ‘new University papers, so.that students can get an idea about university questions Patterns, | be https://www.instagram.com/ranjan_mahato_rkm//Iwww.instagram.com/ranjan_mahato_rkm/_, POPULAR PUBLICATIONS , INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING Very Short Answer Type Questions 4. Which one of the following statements is wrong? [WBUT 2012, 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 derived class Answer: (b) 2. Out of the following which one is not correctly matched? —_ [WBUT 2012, 2015] ‘a)Int-24 bits b)Short-16bits _c) Double-64bits —_d) Byte—8 bits Answer: (a) 3. In which memory a String is stored, when we create ‘a string using new operator? [WBUT 2022} Answer: Heap Memory 4. Out of the following which one is not correctly matched? [WUT 2022] a) JAVA - Object Oriented Language b) FORTRAN ~ Object Oriented Language ¢) C++ — Object Oriented Language d) BASIC ~ Procedural Language Answer: (c) 5. Consider the following 2 statements (S1 and S2). [weUT 2022] ($1) C++ uses compiler only (S2) Java uses compiler and interpreter both Above statements are true or false? Answer: True Short Answer Tyj estions 1. What do you mean by object-oriented programming? IWBUT 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 https://www.instagram.com/ranjan_mahato_rkm/https://www.instagram.com/ranjan mahato_rkm/ ‘OBIECT ORIENTED PROGRAMMING ite Wain Ase sacl uct tions. ; vier For example, objects can inherit cha serfom object-oriented programming, language (OOPL). Java, C++ and Smalitalk OR, down tho differences. between Procedure-oriented and object-oriented ¢ of programming in which programmers défine not jure, but also the types’ of operations (functions) ¢{ yre..In this way, the data structure becor In addition, programmers can cre; [WBUT 2023] t only the data type of a data hat can be ‘applied to the data mes an object that includes both data and ate relationships between one object and acteristics from other objects. one needs an object-oriented programming are tl tere are also object-oriented versions of Pascal. three of the more popular languages, and PROCEDURAL LANGUAGE OBJECT ORIENTED LANGUAGE More concerned with the processing oF procedures and functions. i) Concemed to develop an object or application based on real time. ii)it is not applicable to procedural language. ii) 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. iii) Here it is possible to expose Data andlor variables to the external entities. iii) Here itis strictly restricted. iv) There is rio communication in procedural language rather its simply a passing values to the Arguments to the Functions and / or procedures. iv) The Objects communicate with each other via Functions. ~ ¥) Itfollows Top Down Approach to, Program Execution, ¥) Itfollows Bottom Up Approach of Program Execution. vi) Thistype of programming uses traditional way of calling functions and returning Values, vi) Object oriented concepts includes Inheritance, Encapsulation and Data Abstraction, Late Binding, Polymorphism, Multithreading, and Message Passing Vil) Examples: £.VB, Perl, Basic, FORTRAN. vil) Examples: JAVA, VB.NET, C#.NET 2 What is the difference between Java and C++ in respect of language functions? * [WBUT 2014) Answer: : : pevhing is an object in Java (Single root hierarchy as everything gets derived. from Taare Object), : : ia-(02S not have all the complicated aspects of CH+ (For ex: Pointers, templates, lo ‘ ‘ m SPerator overloading, structures etc..). A Teno destructors in Java. (automatic garbage collection). oop-3 / https://www.instagram.com/ranjan_mahato_rkm/ &g6://www.instagram.com/ranjan_mahato_rkm/ - POPULAR PUBLICATIONS Java does not support conditional compile (#ifdef/#ifndef type). Thread support is built into java but not in C++. . Java does not support default arguments. There’s no scope resolution operator :: in Ja Java uses the dot for everything, but can get away with it since you can define eleme, only ivithin a class. Even the method definitions must always occur within a clas, there is no need for scope resolution there either. There's no "goto" statement in Java. . , \ Java doesn’t provide multiple inheritance (MI), at Ieast not in the same sense that Cy rent because there are no destructor does. Exception handling in Java is different bece l Java has method overloading, but no operator overloading. The String class does use t + and += operators to concatenate strings and String expressions use automatic typ conversion, but that’s a special built-in case. . Jaya is interpreted for the most part and hence platform independent, 3. What is class? How does it accomplish data hiding? IWBUT 2023) Answer: 3 ‘A class is a template to create objects. Methods and variables declared private cannot b access outside of the class. Those can be only accessed internally; it means that they an hidden from the outside. It makes programming easier because it is guarantied that thos internal information won't be messed up by outside code. 4. 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 date 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: V 1. Creators create new objects of the type. A creator may tike an object as al 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 arid 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 examplé, mutates a list bY adding an element to the end, OOP-4 ttps://www.instagram.com/ranjan_mahato_rkm/Tey , https://www.instagram.com/ranjan_mahato_rkm/ OBJECT ORTE MMING penentation of ADT canta ' Jo? can be different ways to implement an ADT. For exampie, the Li Menai using arrays, or singly linked list or Alle Seeks cas tee ry) i ac loubly linked list. Similarl /, Stack ADT infpaue ADT canbe implemented using aay or inked iss. a ie 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 tack ADT. The head node and the data nodes are encapsulated in the ADT. The calling tion'can only see the pointer to the stack. The stack head structure. also contains a pointer to 0p and count of number of entries currently in stack. bi pseudocode: : i his is a simple way of implementing the Stack ADT using an array. Here, elements are sdéed from left to right and a variable keeps track of the index of the top element. public class Stack { private static final int CAPACITY=10; private int capacity; private int top= 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]; Public boolean isEmpty() ( j | return top<0; w ) Public boolean isFull(){ Gs beidiuitt to eniobaNat return’ size()>=capacity; 7 Public void push(object o) if(size()>=capacity) ( ni System.out.printIn("Stack is EulLe gris, ‘ return; Vi obj [++top]=07 oop-s ‘ https://www.instagram.com/ranjan_mahato_rkm/J/www.instagram.com/ranjan_mahato_rkm/, POPULAR PUBLICATIONS public Object pop() { ; 7 i£(isEmpty()) xeturn’ "Stack is empty."; Object temp; temp=obj {top obj [top-~ return temp; ull; y 5. What is Stack ADT? [MODEL QUESTION Answer: A ‘ 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 ¢ pointer to top and count of number of entries currently in stack. by Physical Swucture 2) Conceptal stack ‘count stackMax —top_ 4) X OE Ea I = alco i ofc — ce ‘A Stack contains elements 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. + peck() — 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()—Retum true if the stack is empty, otherwise return false. + isFull() —Return true if the stack is full, otherwise return. 6. Write the functions of the List ADT.” [MODEL QUESTION] Answer: A list contains elements of the same type arranged in sequential order and following ‘operations can be performed on the list. «get()—Return an clement from the list at any given position, insert() — Insert an element at any position of the list. remove() — Remove the first occurrence of any element from’a non-empty list. removeAt() — Remove the element at a specified location from a non-empty lis- replace() — Replace an element at any position by another element. OOP-6 https://www.instagram.com/ranjan_mahato_rkm/y https://www.instagram.com/ranjan_mahato_rkm/ OBIECT ORIENTED PROGRAMMING + size()— a the number of elements in the list. + isEmpty()~ Retum true if the list is empty, otherwise return fal: + isFull() — Return true if the list is full, otherwise return false. “ The List ADT Functions is given below: User Prosram main compare ‘ADT Public Funcsions create list traverse retrieve Node destroy list list count Empty list full list Add Node Search ist remove Node insert search, delete Private Functions 7. What is Queue ADT? Explain its operations. | Answer: [MODEL QUESTION] The queue abstract data type (ADT) follows the basic design of the stack abstract data ‘ype. Each node contains a void pointer to the data and the link pointer to the next foal in the queue. The program’s responsibility is to allocate memory for storing the OoP-7 , https://www.instagram.com/ranjan_mahato_rkm/s :/ www.instagram.com/ranjan_mahato_rkm/ POPULAR PUBLICATIONS) Doi) ophe] ') Conceptual Tn ee ny by Physical Seuicture 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. ‘+ peck()~ 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 retum false. ¢ _ isFull()— Return true if the queue is full, otherwise return false. 8, Define: Abstraction function. [MODEL QUESTION] Answer: Anabsttaction function maps a'state 3f ‘the “concrete machine to’ a. state of the abstract machine. It explains how to interpiet'each state of the concrete machine as 2 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:R—+A OOPSse https://www.instagram.com/ranjan_mahato_rkm/ © .QBIECT ORIENTED PROGRAMMING ares in the diagram show the abstraction function. + properties WE discussed above can be expressed saying that the function is surjective (also called onto), not necessarily bijective’ (also called one-to-one), and often partial, 2, Arep invariant that maps -rep values to IS: Hl an Fora rep value 1, 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. Alternatively, you can think of RI as‘a set: it’s the subset of rep values on which AF is defined. In the terminology of functions, R A 9, Define: Concrete invariant. [MODEL QUESTION} Answers . Aninvariant is a property of a program that is always true, for every possible runtime state of the program. ‘ : ‘ Long Answer estions ‘ i ae {.Write short note on Abstraction. || [WBUT 2014, 2016, 2022) Answer: | ae . ; 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. i on ara * Abstraction is the ‘process of hiding the working style of an object, and showing the information of an object i understandable manner... )seiso0A ne oso Houle aiw § Real world/Example of Abstraction: Suppose we have an object Mobile Phone. eens Suppase'we have 3 mobile phones as following: i 1 ane hah Nokia 1400 (Features:- Calling, SMS) ' " fermen Nokia 2700 (Features:- Calling, SMS, FM:Radio, MP3, Camera). 5 angi Black Berry (Features:-Calling, SMS, FM, Radio, MP3, Camera, Video Recording, Reading E-mails) Fic aig 4 6 seat danny: : ct information (Necessary and Common Information): for the object "Mobile ne" js make a call to any.number and.can send SMS." vy.iy nie ik al, for mobile phone object we will-have, abstract class like following; © Wal (uact. class NobilePhone PIbLLs Gos 1 malig void, calling() # te void senasms(); - magn -eliersties Gift (OOP-9 https://www.instagram.com/ranjan_mahato_rkm/ -J//www.instagram.com/ranjan_mahato_rkmA, POPULAR PUBLICATIONS public class Nokial400 : MobilePhone ( ) public class Nokia2700 =: MobilePhone t public void FMRadio(); public void MP3(); public void Camera (); ) : MobilePhone public class BlackBerry public void FMRadio(); public void MP3(); public void Camera(); public void Recording(); public void ReadAndSendsmails(); } : ‘Abstraction means putting_all the variables and methods in a class which are necessary. For example: Abstract class and abstract method. the common thing: Abstraction example: If somebody in our collage tell us to fill application form, we will fill. our details ike 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 | 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 cons called abstract class. That class is not complete and it can inherit by other class. like name, jist of common thing that is 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 som programming language, independent of an implementation. The interface for the ADT defined in terms of a type and a set of operations on that type. The behaviour of cach operation is determined by its inputs and outputs. An ADT does not specify how the type is implemented. These implementation details are hidden from the user of the 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 tke Java, an ADT and its implementation together make up a class. Each operation associa with the ADT is implemented by a member, function or method. The variables that defire. the space required by a data item are referred to as data members. An abject © instance of a class, that is, something that is created and takes up storage durité execution of a computer program. OOP-10 ps://www.instagram.com/ranjan_mahato_rkm/+ https://www.instagram.com/ranjan_mahato_rkm/ Application Programs Iverface Data Structures Amay Linked list Abstract data Types are three types. 1. List ADT 2. Stack ADT 3. Queue ADT. 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 GE nooe | nape ge. list C ae Pel tt pe me ae 2. Stack ADT: . ; : i 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 totes to top and count of number of entries currently in stack, . Queue ADT i e YT) follows the basic design of the stack abstract data Hid rapier eee va Viner to the data and the link pointer to the next cement in the queue. The program's responsibility is to allocate memory for storing the ta, . https://www.instag ramccom/ranjan_mahato_rkm//www.instagram.com/ranjan_mahato_rkml, POPULAR PUBLICATIONS FEATURES OF OBJECT ORIENTED PROGRAMMING ‘Very Short Answer Type Questions 1. All classes in Java are the sub-class of [WwBUT 2007, 2015 2)Finalelass _b) Object class. ¢) Static class 4) Super class Answer: (b) 2, Inwhich class is the wait () method defined? [WBUT 2007, 2019) 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? a) package, import, class ¢) import, package, class ‘Answer: (a) [WBUT 2010, 2012, 2015, b) class, import, package d) package, class, import 8 having more than one super class is called [WBUT 2017] tegory ) Classification ¢) Combination d) Partial participation Answer: (a) 5. What is the output of this code fragment? (WBUT 2012, 2015] 4. int x= 3; int y= 10; 2, System. out. printin (y% x); a)o b)4 2 gs Answer: (b) 6. Byte code of javais “ UT 2014] a) platform dependent b) platform independent i ¢) no specific rule, d) depend upon oS Answer: (b) 7. Java virtual machine is ’ [WBUT-2044, 2018] a) platform dependent totally b) independent ©) depends on machine architecture only d) depends on OS only Answer: (c) ! 8, Java is robust because [WBUT 2014) a) it is object oriented ' b) garbage collection Is present ¢) platform independent d) exception handling Answer: (d) - [WBUT 2014, 2015] ©) partially ) alther (b) or (¢) / 9. Constructor can be overloaded a) never b) always . OOP-12 ps://www.instagram.com/ranjan_mahato_rkm/| rn ‘ https://www.instagram.com/ranjan_mahato_rkm/ OBJECT ORIENTED PROGRAMMING paseer: (BF %GHG tery gy sown torn t9 40, Which of the following cannot be used for a variable name Is Java? ‘ " BUT 2016] 2) Identifier b) BRA ¢) Identifier & Keyword a Nene tidal ests Answer: (b) 44. What is the range of the char type? 16 2) 0to 2" ) 0 to 2° ©) 0to 24) Hoe goer u ‘Answer: (a) a 42. 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 ¢) anon-comment statement and can be defined anywhere in the program d) none of these v ‘Answer: (a) 43. Which of the following values can a Boolean variable contain? [WBUT 2016] a) True & False b)O&1 ¢) Any integer value vd) True Y Answer: (a) , , 14. What is the output of this program? sit ah [WBUT 2016) class area { ‘4 public static void main (String args[]) double r, pi, a7 i r=9.8; Bt Ide pis3.14; a=pitrtr; * System.out .printin(a)7, Jug ebrewant: y i in yor y : ame a) 301.5656 301 c) 301.56... ,., , d)3014.56560000 Answer: (a) ae 18, How lic class can be allowed in Java? go. DNBUT 2017] a) One pubis Oy Two... ,, c) Many : d) None of these Answer: (a) > 1 yas 18. Whether Java need compiler or interpreter . [WBUT'2017) a) compiler b) interpreter ©) both (a) and (b) " = ppd) Mone ofthese, |, sa Wer: (c), - Sonia 17. Doos any Java program contains more than one main method? [WBUT 2017] a) Yes b) No ,OOP-13 https://www.instagram.com/ranjan_mahato_rkm/5:/www.instagram.com/ranjan_mahato_rkm/ ~ POPULAR PUBLICATIONS c) Sometimes it is possible d) In different package Answer: (a) 48. AWT package is uses for [WBUT 2017, a) Component and graphics b) Component c) Graphics d) None of thess Answer: (a) , 49, Whatis bytecode in context of Java? [WBUT 2019) 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 d) It is the code written within the instance methods of a class Answer: (b) 20, Which of the following statements regarding static methods are correct? [WBUT 2019] a) Static methods are difficult to maintain, because you cannot change their implementation called using an object reference to an object of the b) Static methods can be class in which this method Is defined Static methods are always public, because they are defined at class-level Static methods do not have direct access to non-static methods which are defined inside the same class Answer: (b) or) d) [WBUT 2018] 21. Given the flowing piece of code public class C{ public abstract double calc_sa( ); } 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: (4) ; 22, A subclass is placed in a different package than the super class. In order to fy the correct allow the subclass access a method defined in the super class, identi /BUT 2018] access specifiers(s) a) protected b) public c) private 4) default ‘Answer: (c) . 23. Which of the following keywords are used to contro! adcess to a class member? [WUT 2022) a) New b) Abstract ¢) Publle d) Interface Answer: (b & c) * OoP-14 “https://www.instag ram.com/ranjan_mahato_rkmi—Ritps J/www.instagram.com/ranjan_mahato_rkm/ OBJECT ORIENTED PROGRAMMING abstract class, which declared with the “abstract” keyword, cannot be 4 crtiatod. True or False? TWBUT 2022] Answer Tre x : aq package is a collection of classes, int ‘i 0 3 ostatement is true or false? etfacen amet i haat re aoa answer: THC . g. Which of the following statements is valid array declaration? BUT 2022] a)intnumber() b) floataverage ] __c) int marks Saat int 0 ‘Answer: (b) "i q7.Javais robust because [WBUT 2022] a) itis object oriented b) garbage collection is present ¢) inheritance is present d) exception handling Answer: (b & d) . 28. Give an example of illegal identifier. [WBUT 2023] Answer’ ~ Worid@ Thisis invalid as @ character is not allowed. 29. What is bytecode in context of java? [WBUT 2023] Answer: : Java bytécode is the instruction set of the Java virtual machine (JVM), the language to which Java and other JVM-compatible source code is compiled, 30. Arrays in java are objects or classes? [WBUT 2023] Answer: isibe ‘ Arrays are objects 34. What cannot be used for. variable name in java?“ vary) [WBUT 2023) Answer: We can’t use any of the keywords’or-reserved words as variable'names'in ‘Java ( for , if thss, static, int , double , etc). What is a package in java? * poe}oio sent) BUT 2023] Auswer: ‘ Ajnvapuckege is a group of similar types of classes, interfaces and sub-packages. uly java is called robust programming language? \ )WBUT 2023] Wer: me ‘ eat ‘vais robust because it utilizes strong memory management. 4 Exception created by try block Is caught In which block? IWBUT 2023} | ‘OOP-15 Ce https://www.instagram.com/ranjan_mahato_rkm/POPULAR PUBLICATIONS: Answer: The catch ‘block catches’ and handles the try block exceptions| by declaring the type a within the parameter. a ‘Short Answer Type 4. Differentiate between association and aggregation. Answer: https://www.instagram.com/ranjan_mahato_rkm/ estion: [WBUT 2008, 2007, 2046, ‘ASSOCIATIO’ "AGGREGATION. ? beiween two association is a relation: Aggregation is @ special case, of association jon defines the multiplicity between objects... for example; one-to-one, one-to-many, many-to-one,, many-to-many all these words define an association between objects ‘A _ directional,_association between Objects. When an object »‘has-a" another object, then you have got_an_aggrepstion between them. Direction between them specified which object contains the other object. Agaregation is also called, a “Flas” relationship. : iii) Denoted by, iii) Denoted by, ——_. ™ a Ta] wiectes = _ On [Maza] [7 TRtenor jsheig eae auboeriber "stbserbed magazi FrisiOrStudents ist "Stade Class diagram example of association between two class Class diagram showing Aggregation beest two classes 2. Explain various access modifiers (public, protected, private, default) in a class definition. [WBUT 2006) OR, What isthe difference between’ default access “specifier and: public acs specifier? Explain the differences’ between the ‘private’ and ‘protected access spec! java. oR, Differentiate\between protected and friendly access specifier. Answer: (One of the techniques, in object-oriented programming is encapsulation. It 0 [weur 2013) (WBUT 2018) 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 minim allows you to conirol access to classes, methods, and fields via so-called specifiers. Java offers four access specifiers, listed below in decreasing accessibilit = public He siaitie * protected OOP-16 https://www.instagram.com/ranjan_mahato_rkm/https :/Iwww.instagram.comira njan_mahato_rkm/ TORIENTED PROGRAMMING «default (no specifier) = : «private We look at these access specifiers in more detail, lic publicclasses, ‘methods, and fields can be accessed from everywhere, The onl constraint is that a file with Java source code can only contain one sab fe class hase mame must also match with the filename, If it exists, this gublteches represents the application or the applet, in which case the publ ic keyword is necessary to able your Web browser or appletviewer to show the applet. You use public classes, methods, of fields only if you explicitly want to offer access to these entities and if this access cannot ony ee An example of a square determined by the position of its upper-left corner and its size: public class Square { // public class public x, y, size; // public instance variables } 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 itis appropriate fora 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 * ita a 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 thepublie 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 corner of a square can be set or obtained by accessor methods, but individual Coordinates are not accessible to the user. // public class // peivate (encapsulated) instance Public class square ( Private double x, ¥ Variables ~ OOP-17 https://www.instagram.com/ranjan_mahato_rkm/-/Iwww.instagram.com/ranjan_mahato_rkml, POPULAR PUBLICATIONS public setcomer(int x, int y) ( // setting ‘dues Of'privarg fields fi this.x = x; into one ‘ , this.y = y; } 5 ‘ oalun “a public getCorner() { // setting, values of, private .fields return Point(x, y); ? u . ” Stummary of Access Specifiers 5 i The following table summarizes the access level permitted by each specifier, Situation public | protected | default | private ‘Accessible to class yes yes ‘yes m0 from same package? Accessible to class ~ yes | no,unlessitisa] no 70 from different package? subclass “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 ae part of the same package. They are not visible to subclasses unless these are in the sane package. protected methods and variables are visible to subclasses regardless of which package they are in v8 3. State the Difference between the following: Static and final keyword IWBUT 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, G A final variable can only be initialized once, cither 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, itis useful to declare them as final. : The keyword "static" when applied to a variable OR a method means that th varigble ot method can be accessed without creating an instance of the class, For'examples of’static variables see the Color class in the Java’ API. It uses static variables such as BLACK, BLUE, PINK ‘etc, J They ean be referenced like: Code: useColor (Color. BLACK) ; instead of Code: Color myColorBlack = new Color (|); oop-18’ ps://www.instagram.com/ranjan_mahato_rkm/ry https://www.instagram.com/ranjan_mahato_rkm/ OBJECT ORIENTED PROGRAMMING yseColor (myColorBlack. BLACK) ; static can be used for methods for much the same effect. 1 1 When “final” is applied to 2 class, the principle effect is that the class cannot be inherited from. For example, the following would throw an error; de: colic final class Dog ( public Dog(). } Viaie class JackRussell extends’ Dog { public JackRussel1() ( } } 4, Differentiate between Early binding and late binding: [WBUT 2010, 2018] What is the difference between static binding and dynamic binding? [WBUT 2011] Answer: Late Binding: .* Atrun 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 function will be called, though early binding is faster than late binding: Early Binding: a © The overloaded member functions are 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 E * Early binding determines execution path at compilation and late binding allows for dynamic execution at runtime. : . for example: In a native Win32 code environment (j.e., non .NET), late binding could refer to the use of a DLL library ys. 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, * S.Whatare the main characteristics of OOP Language? Explain each. [WBUT 2012] om https://www.instag@fr¢om/ranjan_mahato_rkm/ps://www.instagram.com/ranjan_mahato_rkm/ _ ULAR PUBLICATIONS Answer: Encapsulation: aan ji In programming, it is the process of combining elements to create 2 new entity. Fo, example, a procedure is a type of encapsulation because it combines a series of compe, instructions, Likewise, a complex data type, such as arecord or class, relies oq encapsulation, Object-oriented programming languages rely heavily on encapsulation 1p create high-level objects. Encapsulation is closely related to abstraction and information hiding. ha ais . 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. Itis even ‘possible 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 moduiles. Polymorphism: In object-oriented programming, polyinorphism (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 as a variable, a function, or an object to have more than one form. There are several different kinds of polymorphism. 1) A variable with @ 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 either an integer (whole number) oF a string of characters (perhaps because the programmer wants to allow a user to enter user ID as either 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 han¢led in each 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 isan integer, the function chosen would be to seek a match agallst a list of employee numbers; if the variable were a string, it would seck a match against ® list of names. In either case, both functions would be known in the program by the samt name, This type of polymorphism is sometimes known as overloading. ; You drive an automobile, which has properties like wheel size, engine size, gas tank sit, ‘and ther properties. The automobile you drive is a concrete implementation the automobile interface, It has additional features, like sliding doors, logo {yPe> 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 litt OOP-20 https://www.instagram.com/ranjan_mahato_rkm/vy | https://www.instagram.com/ranjan_mahato_rkm/ | a OBJECT ORIFNTED PROGRAMMING I ose door, open trunk, turn- wheel, and other -behaviors that would be specific to an | qyromabile. . . i jroo programming, using the automobile example, Automobile would be the base class, ‘each automobile manufacturer would have its own implementation. For: instance, Honda has V-Tee technology, which is in its own implementation. Volvo uses diesel ines. Which is the TDI technology. More importantly, you may add an‘added level of Saail between automobile and the make/model implementation, such as Car, Truck, or sav super types, tO provide more relevant information. Inheritance: : 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 jéditional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional tain ring, giving them a lower gear ratio, Object-oriented programming allows classes to inherit commonly used state and behavior fom other classes. In this example, Bicycle now becomes thesuperclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses: . Bicycle MountainBike - RoadBike TandemBike Ahierarchy of bicycle classes. as i : The syntax for creating a subclass is simple. At the beginning of your class declaration, Ise the extends keyword, followed by the name of the class to inherit from: . Class Mountainbike extends Bicycle { : Ht new fields and methods defining a mountain /bike,would go here ) ds and methods as Bicycle, yet allows its code t make it unique. This makes code for your properly document the state and This gives MountainBike all the same fe focus exclusively on the features tha ‘ubclasses easy to read. However, You must take care to oop-21 https://www.instagram.com/ranjan_mahato_rkm/https ://www.instagram.com/ranjan_mahato_rkm/ POPULAR PUBLICATIONS bbchavior that each superclass defines, since that code will not appear in the source ig each subclass. 6. What do you meant by ‘Dynamic Method Dispatch’? DWBUT 2015, Answer: ; Refer to Question No. 10(a) of Long Answer Type Questions. 7. What is message passing? [WUT 2018) Answer: ; | ; Massage passing is a form of communication used in object-oriented programming ay ing : i is like sending an object well as parallel programming : Massage passing in Java is biect ie estan from one thread to another thread. It is used when threads do not have shared ) memory and are unable to share variables to communicate. Thread | 1 (Producer) Panmassige| "Blocking Queue | Get massage 1 I 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: r A Java Program to show use of abstract class and Interface: interface MyInterface f void methodl (); void method? \(); class Demo implements MyInterface C Be public void method1 (); C System.out.println ("implementation of methodl"); ) public void method2 ‘(y; ' { i nM t System.out.println ("implementation of method2"); d OOP-22 https://www.instagram.com/ranjan_mahato_rkm/https://www.instagram.com/ranjan_mahato_rkm/ ‘OBJECT ORIENTED PROGRAMMING poli istatic void main (String axgsis)), ' yyinterface obj = newDemo (); nent opjemethodl(); o ‘ vowe te nll ’ “ ) 9, What is qualified association? Describe with ah'example. ° - [WBUT 2022] Answer? : Aqualifier 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 aqualified association. Depicting ‘a qualifier in 2 domain model communicates how, in’ the domain, things of one class are distinguished in relation to another class. Example Qualified Association: Canvas & Figure 0.8 Cainvas Figure id Figure 10. What is an object? Why Java is called an object oriented language? x [WBUT 2022} Answer: 1" part: 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 and all those objects will get the same fields and behavior. Student s1 = new Student(); i 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, 8l.id=12 82.age: 53.course= computers”; ™ part: ‘ a Java Language is considered. an- object-oriented language because it, is based on .the Concept of objects and classes. Without the creation of objects and classes, it is Impossible to write any code in Java. Java supports the concepts of OOPS - Inheritance, ta abstraction, polymorphism, and data encapsulation. https://www.instag r&9h@bm/ranjan_mahato_rkm/:/Iwww.instagram.com/ranjan_mahato_rkm/_, POPULAR PUBLICATIONS 14. Explain static keyword with suitable Java code. BUT omy Answer: ‘The static keyword in Java is used for memory management mainly. We can apply Stitie keyword with variables, methods, blocks and nested classes. The static keyword belong 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 as a class method) 3. Block 4, Nested class r 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 ( ring name t xollNo; // static variable static String cllgName; // static counter to set unique roll no static int counter = 0; public Student (string name) i this.name = name; : this.rollNo = setRollNo(); d 7) getting unique rol1No 7/ through static variable (counter) static,int setRollNo() £ counter++; return counter; } 7/ static method 5 static void setCllg(String name) { cllgNarie = name; } // instance method void getStudentInfo() C : "+! this.name) ; system. out.printin ("name * + this.roliNo); system.out.printin("rollNo : // accessing static variable System.out.printin(*cllgName : " + cllgName); oop-24 ps://www.instagram.com/ranjan_mahato_rkm/ “https://www.instagram.com/ranjan_mahato_rkm/ QUIECT ORIENTED PROGRAMMING Hi priver class plic class StaticDemo { pl public static void main(String{} args) { // calling static method / without instantia sty student.setClig(*xyz"); sent Class Student si new Student (*Alic, icet); Student s2 new Student ("Bob"); , si.getStudentInfo(); s2.getStudentInfo(); ) Output name : Alice rollNo : 1 dligName : XYZ name : Bob rollNo : 2 clipName : XYZ . wield 12. What is constructor? : [WBUT 2023] A constructor in Java Programming is a block of code that initializes (constructs) the state and value during object creation. It is called every time an object with the help of a new () keyword is created. Even if you haven't specified any constructor in the code, the Java compiler calls a default constructor. The default constructor is used to assign default states and values, such as 0, null, etc.,-to the object. The general syntax of a constructor is: class ClassName{ SiasemamhC) ( //ereating a constructor . 0 j . Example: ‘lass Main: ( Private String name; 11 constructo: ro Main() ( System.out.printin(*"Constructor Called: *); name = *Program"; https://www.instag ram.com/ranjan_mahato_rkm/-/Iwww.instagram.com/ranjan_mahato_rkmL, POPULAR PUBLICATIONS: public static void main(string!] args) ( ‘V/ constructor is invoked while // creating an object of the Main-class Main obj = new Main(); system.out.printin ("The name is "+ obj.name); ) } ‘Output: Constructor Called: The name is Program ‘ [MODEL QUESTION) agit 13. Write down in brief about polymorphism. Answer: e Itis the concept where an object behaves differently in different situations Since the object takes multiple forms, it is called Polymorphism. In java, we can achieve it using method overloading and method overriding. «There are 2 types of Polymorphism available in Java, { Method overloading Wg 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 wT" ided at the run time, time,based on. what method overloading. Method overriding In-this case, which method to call will be deci object is actually pointed by the reference variable. fo give 4. a) Explain role name in an association with example. [WBUT 2004] OR, Discuss association. j [WBUT 2013) b) What is aggregation? How. aggregation is different from association ané generalization? [wsuT OR, [wBUT.2013) Discuss aggregation. Answer: a) An association implies two model elements have a relationship - usually implemented roles at each e as an instance variable in one class. This connector may include named cardinality, direction and constraints. Association is the general relationship type B2UWe elements. For more than two elements, a diamond representation toolbox element can used as well, When code is generated for class diagrams, named association ends bec instance variables in the target class, So, for the example below, "playsFor" will an instance variable.in the "Player" class. OOP-26 me https://www.instagram.com/ranjan_mahato_rkm/v https: ays For, 1 ‘An.association end role is a specialization of an association’ end, used to describé an association end’s behavior in a particular context. Inthe UML metamodelAssociationEndRole is a sub-class of AssociationEnd. ‘Two or more association end roles are associated with each association role. Clesses can also contain references to cach other. The Company class has two attributes that reference the Client class. _ ‘Company name: String ‘ -contactPersonClient employees: Client{) Although this is perfectly correct, as associations is sometimes more expressive to'show the attributes Contact Person ot 2 1 ie Client : asta : String name : Str sfirsinameString [5 4,29) ¢ -email; String employees oe 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 contactPerson 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: : i 0 Zero j 1 _ One Lit 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 Stamples, the Company references Clients, but theClientclass does not have any Knowledge of the Company. You can set'the navigability on either, neither or both ends f your associations, If there is no navigability shown then the navigability is unspecified, OOP-27 /Iwww.instagram.com/ranjan_mahato_rkm/ EC RI https://www.instagram.com/ranjan_mahato_rkm/POPULAR PUBLICATIONS 5:/Iwww.instagram.com/ranjan_mahato_rkmk b) Difference between Association and Aggregation: : Refer to Question No. 1 of Short Answer Type Questions. Difference between Agercgation and Generalization: AGGREGATION GENERALIZATION 1) A directional association between objects. When an object *has-a° another object. then you have got an aggregation between them. D Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behavior are used from the specialization to the encralized class. At a very broader level we can understand this as inheritance. ii) Denotes by, —_—_> ii) Denotes b; — Tr means for example one College is build up of Departments and again departments contains classes right here school aggregation of departments again department is aggregation of classes, here you ccan perfect aggregation of things if you delete the main object called school all associated departments and classes will get delete. and Ti) Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization. 2, What are the differences between ‘abstr: act class’ and ‘interface’? [WBUT 2005, 2007, 2009, 2010, 2011, 2013, 2018, 2027] Answer: Abstract class Interface T. | 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 read only class. 2. | 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. 3. | A new abstract class cannot be fitted easily | Multiple classes can implement a rew 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 1 i 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. own _as_single | and at the same time can extend a class fot OOF ittps://www.instagram.com/r P28 ‘anjan_mahato_rkm/ttps://www.instagram.com/ranjan mahato rkm/ Abstract dass Tnter Frectional inheritance, Rinkaax s «nixed 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. , oR [WUT 2044] 2) What do you mean by parameter passing? ) What is the difference between call by value or pass by value and call by reference or pass by reference? Explain, [WBUT 2015) Answer: 1 Part: Parameter passing is the mechanism used to pass parameters toa 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 been devised, notably call by name in Algol 60, where the actual parameter is re- evaluated each time it is required during execution of the procedure. 2™ Part: In programming, there are two ways to pass arguments to'a method, call-by-value and call-by-reference: © When we have a call-by-value parameter, a copy of the argument is stored into the memory location allocated for the formal parameter. In this case, any changes made to the formal parameter inside the method will not affect the value of the argument back in the calling method, When a parameter is call-by-reference, the memory address of the argument is passed to the method, making the formal parameter an alias for the argument. This means that changes made to the formal parameter inside the method ‘will be reflected in the value of the argument when control is retumed to the calling function. 3"Part: There is only call by value in java, not call by reference. If we'call a method passing a Value, it is known as call by value. The changes being done in the called method, is not affected in the calling method: i Example of call by value in java ' 888 Operation{ Ant data=5 : oop-29 https://www.instagram.com/ranjan_mahato_rkm/J//www.instagram.com/ranjan_mahato_rkm/ - POPULAR PUBLICATIONS void change(int! data) ( data=data+100;//changes will be in the local variable only } public static void main(String args[]){ Operation op=new Operation(); System.out.printin ("before change "+op.data); op. change (500) ; Systemsout-printin ("after change '"+op.data) ; } 1 Output: before' change'50 after change 50 Another Example of call by value in java y In case of calll by reference original value is changed if we made changes’ in the called method. If we pass object in place of any primitive value, original value will be changed, In this example we are passing object as a value. Let's take a simple example: class Operation2( int data=50; void change(Operation2 op) ( op.data=op.data+100;,//changes will be in the instance variable ) public static void main(string args{]) ( Operation2 o) ew Operation2(); System.out.println("before change "+op.data); op.change(op) ;//passing object ‘ system.out.printIn(‘after change "+top.data); ) ) Output: before change 50 after,change 150 4. What are the different characteristics of abstract keyword? Explain abstract class through a program, ‘| [WBUT 2015] Answer: 1" Part: The “abstract” keyword can be used on classes and methods. A class declared with the “abstract”. keyword cannot be instantiated, and that is the only thing the “abstrad” keyword does. Example of declaring a abstract class: © abstract Calendarsystem (String name) ; When a class is declared abstract, then, its methods may also be declared abstract. When a method is declared abstract, the method can,not have a definition, This is the only effect the abstract keyword has on method. Here's a example of a abstract method: abstract. int get_person_id (String name); OOP-30 ttps://www.instagram.com/ranjan_mahato_rkm/ttps://www.instagram.com/ranjan_mahato_rkm/ QOBIECT ORIENTED PROGRAMMING pstract classes and abstract methods are like skeletons. It defines a structure, without any implementation. only abstract classes can have abstract methods, Abstract class does not necessarily require its methods to be all abstract, classes declared with the abstract ki eyword are solely fa f extension {aheritance) by other classes. The cha it ead ita ein characteristics of abstract class are given below: 1) Abstract class cannot be instantiated, but pointers and references of Abstract class type can be created, Abstract class can have normal fu; function. Abstract classes are maint its interface. 4) Classes inheriting an Abstract Class else they will become Abstract too, 2 inctions and variables along with a pure virtual 3) ly used for Upcasting, so that its derived classes can use must implement all pure virtual functions, or 2" Part: The purpose of an abstract class is to specify the default functionality of an object and let its sub-classes to explicitly implement that functionality. Thus, it stands as an abstraction layer that must be extended and implemented by the corresponding sub-classes. A sample example of using an abstract class is the following. We declare an abstract class, called Instrument: Instrument.java: abstract class Instrument ( protected String name; abstract public void play(); : ee, } ‘4s we can observe, an Instrument object contains a field name and a method called play, that must be implemented by a sub-class. ; Next, we define a sub-class called Stringedinstrument that extends the instrument class and adds an extra field called numberOfStrings: StringedInstrument . java: astract class Stringedinstrunent extends Instrument € Protected ‘int numberOfStrings; Finally, we add two more classes that implement “the functionality of Stingedinstrument, calledElectricGuitar and FlectricBassGiitar accordingly. The definition of these newly added classes is shown below: ' Bectriccui tar java; ; ue class ElectricGuitar extends Stringedinstrument ns Bipees eeectrieGuitar() ( ae ‘ per () " ' te Rane = "Guitar"; ilad Wi ) “Pumberofstrings = 6; ! ‘OOP+31. . , https://www.instagram.com/ranjan_mahato_rkm/https://www.instagram.com/ranjan_mahato_rkm/ POPULAR PUBLICATIONS. public ElectricGuitar(int numberofstrings) ( super (); this.name = “Guitar”; this. numberofStrings = numberofstrings; ) @override public void play() ( System.out printin(*An electric " + numberofSstrings + ‘-string » + name + * is rocking! "); ») ElectricBassGuitar.java: itar extends StringedInstrument { public class ElectricBass6u! public ElectricBassGuitar() ( super (); this.name = "Bass Guitar" this.numberofStrings = 4 ) public ElectricBassGuitar(int mumberOtstrings) y super ();. this.name - ‘Bass Guitar"; f this. numberofStrings = numberOfStrings; } override public void play() ¢ Eyeten.out.printIn(*an electric *,+ numberofstrings +. *-string ° + nane . 4" is rocking!"); By that contains a single main method: Finally, we create a new class called Execution Execution.java: import main. java.music-BlectricBassGuitar: jmport main. java.music.£lectriccuitar; public class Execution ( public static void main(string{].ergs) { ElectricGuitar guitar new ElectricGuitar(); ElectricBassGuitar bassGuitar = new ElectricBassGuitar (); guitar -play(); passGuitar-play(); = new FlectricGuitar (7); guiter = bassGuitar = new ElectricBassGuiter (5); guitar-play(); passGuitar. play() - ” ; : a casa In this example, we create two different instances of an BlectricGuitar te ElectricBassGuitar classes and we call their play methods, A sample execution 0! aforementioned main method is shown below: An electric 6-string Guitar is rocking! An electric 4-string Bass Guitar is rocking! OoP-32 _ https://www.instagram.com/ranjan_mahato_rkm/yr. : https://www.instagram.com/ranjan_mahato_rkm/ ‘QUIECT ORIENTED PROGRAMMING electric q-string Guitar is rocking! m Srectric S-string Bass Guitar is rocking! cuss the differences between the following: 5. Oe and ‘throws’ clause cS [WBUT 2022] 9 inal and finally Answer! "se Basis of Differences throw how I ie Java Throw keyword 1s | Java throws keyword is used throw an exception | used in the method explicitly in the code, inside the function or the block of code. signature to declare an exception which might be thrown by the function while the execution of the code, 2 _| Type of exception Using Using throws. keyword, ,| throw keyword. we can we can declare both only propagate | checked and. unchecked {unchecked exception i.e. | exceptions. However, the the checked exception | throws keyword can be cannot be propagated | used to propagate using throw only. checked exceptions only. 3” | Syntax The throw keyword is| The throws keyword is followed by an instance | followed by class names of Exception to be| of Exceptions to be thrown. thrown. 4 Declaration Throw is used within the | Throws is used with the method method signature. We can declare multiple exceptions using throws keyword that can be thrown by the method. For example, main() throws IOException, SQLException. We are allowed to throw only one exception at 2 time i.e, we cannot throw multiple exceptions. 3 _ | Internal implementation No. Tinal finally 1) Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed. Finally 1s used to place important code, it will be executed whether exception is handled or not. 2) Final is a keyword, Finally is a block. https://www.instag OoP-33 ram.com/ranjan_mahato_rkm/:/Iwww.instagram.com/ranjan_mahato_rkm/~ POPULAR PUBLICATIONS Java final example class FinalExample{ public static void main(String{] args) ( final int x=100; x=200;//Compile Time Error ) } Java finally example class FinallyExample{ public static void main(String[] args) { try{ int x=300; }eatch (Exception e){System.out .println(e);} finally(System.out.println ("finally block is executed"); } ) ) 6. Create a package and write a Java file with four methods for four basic arithmetic operations such as addition, subtraction, multiplication and division. These methods should save the file in the package. Write one more program that imports the above file to use those four methods. [WBUT 2022) Answer: package arithmetic; public class MyMath ( public int add(int, x,int y) { return x+y; ) public int sub(int x,int y) C retum x-y/ } public {nt mul(int x,int y) ( return x*y; } public double div(int x, int y) { : ; return (double)x/y; } ) Note: Move to parent directory, write the following file and execute it. import arithmetic.*; class Test OOP-34 ps://www.instagram.com/ranjan_mahato_rkm/ =~
You might also like
Object Oriented Programming
PDF
No ratings yet
Object Oriented Programming
80 pages
Distributed Database Concepts
PDF
No ratings yet
Distributed Database Concepts
52 pages
Dbms Gate Notes
PDF
No ratings yet
Dbms Gate Notes
574 pages
Chapter 1 Databases and Database Users
PDF
100% (1)
Chapter 1 Databases and Database Users
7 pages
Lecture 12 Structures
PDF
No ratings yet
Lecture 12 Structures
37 pages
Sonali DBMS Notes
PDF
100% (13)
Sonali DBMS Notes
61 pages
Classical Analysis
PDF
No ratings yet
Classical Analysis
6 pages
FirstTwounitsNotes OOSD (16oct23)
PDF
No ratings yet
FirstTwounitsNotes OOSD (16oct23)
97 pages
DSA-Unit 5
PDF
No ratings yet
DSA-Unit 5
39 pages
Computer Networks (1) - 157-172
PDF
No ratings yet
Computer Networks (1) - 157-172
16 pages
Distributed Database
PDF
No ratings yet
Distributed Database
22 pages
DataWarehouseMining Complete Notes
PDF
No ratings yet
DataWarehouseMining Complete Notes
55 pages
Congestion Control and QoS
PDF
No ratings yet
Congestion Control and QoS
8 pages
BDA Unit2 Complete
PDF
No ratings yet
BDA Unit2 Complete
56 pages
VPR - CC - Unit3.2 - Aneka - CometCloud - TSystems - Workflow - MapReduce - PPSX
PDF
No ratings yet
VPR - CC - Unit3.2 - Aneka - CometCloud - TSystems - Workflow - MapReduce - PPSX
67 pages
Se Module 2 PPT
PDF
No ratings yet
Se Module 2 PPT
86 pages
Data Abstraction and Data Independence
PDF
No ratings yet
Data Abstraction and Data Independence
1 page
7 Query Localization
PDF
No ratings yet
7 Query Localization
27 pages
DSA RTU 2022 Paper
PDF
No ratings yet
DSA RTU 2022 Paper
15 pages
Integrity and Security in DBMS
PDF
100% (1)
Integrity and Security in DBMS
58 pages
Unit 2 - Data Structure - WWW - Rgpvnotes.in
PDF
No ratings yet
Unit 2 - Data Structure - WWW - Rgpvnotes.in
22 pages
Unit 4 Cloud Dr. Preeti Patil
PDF
100% (1)
Unit 4 Cloud Dr. Preeti Patil
81 pages
SOFTWARE_ENGINEERING_UNIT-V_(SE_R23_JNTUK)
PDF
No ratings yet
SOFTWARE_ENGINEERING_UNIT-V_(SE_R23_JNTUK)
14 pages
1) Explain Briefly About The Four Major Phases of Unified Process With Neat Diagram. The Four Phases
PDF
No ratings yet
1) Explain Briefly About The Four Major Phases of Unified Process With Neat Diagram. The Four Phases
8 pages
CS-201 Data Structure 3-1-0-4 3 Sem (CSE) Prerequisites: CS-101
PDF
No ratings yet
CS-201 Data Structure 3-1-0-4 3 Sem (CSE) Prerequisites: CS-101
1 page
Indexing
PDF
No ratings yet
Indexing
6 pages
CN and WP Lab Manual
PDF
No ratings yet
CN and WP Lab Manual
101 pages
Device-Independent I/O Software
PDF
No ratings yet
Device-Independent I/O Software
2 pages
Code Optimization
PDF
0% (1)
Code Optimization
90 pages
Question Bank Unit 1 PDF
PDF
No ratings yet
Question Bank Unit 1 PDF
27 pages
Evolution of Computer Architecture
PDF
0% (1)
Evolution of Computer Architecture
6 pages
SE CH - 3 Software Requirement Engineering
PDF
No ratings yet
SE CH - 3 Software Requirement Engineering
4 pages
Dbms Unit 4.2
PDF
No ratings yet
Dbms Unit 4.2
60 pages
PPL Unit 3
PDF
No ratings yet
PPL Unit 3
14 pages
Tentative Questions For The Data Structures Viva
PDF
No ratings yet
Tentative Questions For The Data Structures Viva
5 pages
Oomd QB Answer
PDF
No ratings yet
Oomd QB Answer
62 pages
Cse306 Question Paper
PDF
No ratings yet
Cse306 Question Paper
3 pages
Access Matrix: Implementation and Comparison
PDF
No ratings yet
Access Matrix: Implementation and Comparison
19 pages
The CAP Theorem
PDF
100% (1)
The CAP Theorem
3 pages
UNIT-3: Introduction To Parallel Database and I/O Parallelism
PDF
No ratings yet
UNIT-3: Introduction To Parallel Database and I/O Parallelism
52 pages
Unit II: Software Requirement Analysis and Specifications
PDF
No ratings yet
Unit II: Software Requirement Analysis and Specifications
64 pages
Unit 4
PDF
No ratings yet
Unit 4
153 pages
Unit-II BDA
PDF
No ratings yet
Unit-II BDA
19 pages
Requirements Modeling
PDF
No ratings yet
Requirements Modeling
39 pages
NSK OS I 13 Solution 1
PDF
No ratings yet
NSK OS I 13 Solution 1
7 pages
OS 2 Marks
PDF
100% (11)
OS 2 Marks
15 pages
OOMD Unit-1
PDF
No ratings yet
OOMD Unit-1
81 pages
Web Development Using PHP
PDF
No ratings yet
Web Development Using PHP
65 pages
2 Mark Questions
PDF
100% (1)
2 Mark Questions
3 pages
cs401 PDF
PDF
33% (3)
cs401 PDF
55 pages
DBMS in 5 Hours
PDF
100% (2)
DBMS in 5 Hours
332 pages
Dbms Unit 1 Notes
PDF
0% (1)
Dbms Unit 1 Notes
14 pages
Unit 4 - Data Structure
PDF
No ratings yet
Unit 4 - Data Structure
18 pages
PPL Unit 3-1
PDF
No ratings yet
PPL Unit 3-1
25 pages
Operating System (Questions)
PDF
No ratings yet
Operating System (Questions)
27 pages
Chapter 8
PDF
No ratings yet
Chapter 8
48 pages
OOPs1
PDF
No ratings yet
OOPs1
50 pages
OOP notes
PDF
No ratings yet
OOP notes
117 pages
Abstraction, Encapsulation, Inheritance, Polymorphism: What Are The Features of Object Oriented Programming?
PDF
No ratings yet
Abstraction, Encapsulation, Inheritance, Polymorphism: What Are The Features of Object Oriented Programming?
21 pages
Oops 2 Mark Eduengg
PDF
No ratings yet
Oops 2 Mark Eduengg
42 pages
Getting Started With Enterprise Grade AI Badge20241103-26-t7vhmz Compressed
PDF
No ratings yet
Getting Started With Enterprise Grade AI Badge20241103-26-t7vhmz Compressed
1 page
random_variable_solutions
PDF
No ratings yet
random_variable_solutions
3 pages
Probability_Solutions
PDF
No ratings yet
Probability_Solutions
4 pages
btech-cse-5-sem-software-engineering-esc501-2024
PDF
No ratings yet
btech-cse-5-sem-software-engineering-esc501-2024
2 pages
os 5th sem 2024 organizer
PDF
No ratings yet
os 5th sem 2024 organizer
148 pages