Sei sulla pagina 1di 72

2 Marks and 16 Marks Class : III EEE Subject Code : CS2311 Subject : Object Oriented Programming Part-A 1) Gi e t!

e e olutiononce"tdiagram# o$ OOPS c Machine language Procedure language Assembly language OOPS 2) %e$ine &ecursion' Recursion is the process of defining somethin allows a method to call itself recursi!eAmethod" that int fact#int n$% int result& if #n' '1$ return 1& result'(1$ fact#n)n& return result& * 3) (!at is Procedure oriented language' +on!entional programming (le!ellangusingage suchhigh as +O,O- commonly knownorientedasProcedurelanguage #POP$" .n POP written to accomplish the tasks such as readi

)) Gi e some c!aracteristics-orientedlanguageo$"rocedure# / 0mphasis is on doing things #algorithms$" / -argerareprogramsdi!ided into smaller programs kno / Most of the functions share global data"

/ 1ata mo!e openly around the system from fun / 0mploystop-downapproach in program design" 2unction( 12unction(22unction(3

2unction(4ction(5 2unction(62unction( 62unction(7 Main program

*) (rite an+ $our $eatures o$ OOPS# / 0mphasis is on data rather than on procedur / Programs are di!ided into ob8ects"

/ 1ata is hidden and cannot be accessed by e9 / 2ollowsbottom-upapproach in program design"

,) (!at are t!e basic conce"ts o$ OOS' / Ob8ects" / +lasses" / 1ata abstraction and 0ncapsulation" / .nheritance"

/ Polymorphism" / 1ynamic binding" / Message passing"

-) (!at are objects' Ob8ects are(timebasentitieincrunan(orientedob8ect system" :hey may place a bank account a table of data or any the data and code to manipulate the data and .)(!atis a class' :he entire set of data and(definedcodeofdataan ob8ecttypewi a class" Once a class has been defined we ca classes" +lasses(definedaredataa!eustypesrlike(in andtypesbuiltbehof the pro language"

/) (!at is enca"sulation' ;rapping up of data and function within the s 10)(!at is data abstraction' :he insulation of data fromed directasdataoraccessinformatiohidingby binding" :he data is not accessible to the ou wrapped in the class can access it" 11)(!at are data members and member $unctions +lasses use the conceptdefinedof abs tractionlistofandabstar weight and cost and uses functions to operat called as data members because they hold info areledcalas methods or member functions"

0g< int a b& == a b are data members >oid getdata # $ & == member function 12)(!at is d+namic binding or late binding' ,inding refers to the linking of a procedure 1ynamic binding means that the code associated the time of (timehe"call at the run 13)(rite t!e "rocess o$-oriented"rogrammilanguage'inan obj / +reate classes that define ob8ects and thei /+reating ob8ects from class definition"

/ 0stablishing communication among ob8ects" 1))Gi e an+ $our ad antages o$ OOPS#


:he

principle of data hiding helps the pro be in!aded by code amin" other parts of the p .t is possible to ha!e (multiplee9istwithoutinsancesany i

? Ob8ect oriented programming can be easily ? Software comple9ity can be easily managed" 1*)(!at are t!e$or$eaturbasedobj-ct re1uired"rogramming 2anguag / 1ata encapsulation" / 1ata hiding and access mechanisms" / Automatic initiali@ation and clear up of ob / Operator o!erloading" 1,)(!at are t!e $eatures re1uired $or object / 1ata tionencapsula" / 1ata hiding and access mechanisms" / Automatic initiali@ation and clear up of ob / Operator o!erloading"

/ .nheritance" / 1ynamic binding" 1-)Gi e an+ $our a""lications o$ OOPS A A A A Real(time systems" Simulation and modeling" Ob8ect(oriented databases" A. and e9pert systems"

1.) Gi e an+ $our a""lications o$ c33' / Since cBB allows(relatedusto ob8ects createhierarchywe(orientedcanbuil libraries which can be used later by many pr / +BB are easilyableandmaintaine9pandable" / + part of +BB gi!es the language(le!el thedetailsabilit" / .t is e9pected that(purpose+BBwill anguagereplace in+ asthea 1/) (!at are to4ens' :he smallest indi!idualprogramareunitsknowinfollowingastokenstoke"+ o Ceyword o .dentifiers o +onstants o Strings o Operator 20)(!at are 4e+5ords' :he keywords implement specific +BB language and cannotas namebeus edfro the program !ariables or 0g< go to .f struct else union etc" 21) &ules $or naming t!e identi$iers in C33# / Only alphabetic characters digits and unde / :he name cannothdigistart" wit

/ :he upper case and lower case letters are d / A declared keyword cannot be used as a !ari

22)(!at are t!e o"erators a ailable in C33' All operators in + are also used in on+BB" .n a operator DD the other new operators in +BB ar

Scope resolution operator < < )(to(Pointermember declarator

(D) Pointer(to(member operator ") Pointer(to(member operator delete Memory release operator endl -ine feed operator

new Memory allocationator oper setw 2ield width operator

23)(!at is a sco"e resolution o"erator' Scope resolution operator is used to unco!er !ersion of !ariables" 0g< EincludeFiostream"hD int m'1G& == global !ariable m !oidinma# $ % int m'2G& == local !ariable m coutFFHm'HFFmFFHInH& coutFFH< < InH&m'HFF< < mFFH * out"ut: 20 10#< < m access global m$ Scope resolution operator is used to define t

Synta9< Return type FclassmeDnameD < < Ffunction na 0g< >oid 9 < < getdata#$ 2)) (!at are $ree store o"erators 6or) 7emor+ Jew and 1elete operators are called as free s memory dynamically"

8e5operator can be usedtypeto"create ob8ects of a Pointer(!ariable ' new data type&

.nitiali@ation of the memory using new operat Pointer(!ariable(type#!alue$'newdata

%eleteoprator is used to release the memory spa its use is

1elete(!arpointerable& 2*) (!at are mani"ulators' Setw endl are known as manipulators" Manipulators are operators that are used to f when used in an output statementct causesissimilarlin to that of theInHnewline" characterH

Eg:+outFFsetw#5$FFsumFFendl& 2,) (!at do +ou mean b+ enumerated datat+"e' An enumerated datatype(defindisdatatypanother userwhich pro!i names to numbers comprehensibilitytherebyincreasingof the code" :he synta9enumstatementofan is similar to that of the

Eg: enum shape% circle sKuare triangle* enum color% red blue green yellow* 2-) (!at are s+mbolic constants' :here are two mbolicwaysforconstcreantstinginsy+BB< / Lsing theconstantKualifier#

/ 1efining a set ofenumkeywordinteger" constants using :he program in any way cannot modify the !alu 0g<+onst int si@e '1G&

+har name Msi@eN& 2.)(!at do d+namic+ouean initiali9ationb+ o$ ariable +BB permits initiali@ation(time":hisof theis referred!ariablestoa initiali@ation of !ariables" .n +BB a !ariable(timecan usingbeinitiali@ede9pressionsat atrunth of declaration as

OO"" O"""""" int n 'strlen#string$& OO""

float area'3"14)rad)rad& :hus declaration and initiali@ation is done s is used for the first time"

2/) (!at are re$erence ariable' A reference !ari#ablelt rnati!epro!idesname$analiasfor a pre!i

2or e9ample ifsumamakereferencethe!aritotal thenble !ariable sumandtotcaln be used interchancheably to represe S+nta:< 1a(taype Preference(name'(!ameriable Eg: float total ' 1GG& float sum ' total& 30)(!at is-dere$erencingmmber o"erator' +BB permits to access the class memb(to(emberrsthrou operators for this purpose < <) :o declare a pointer to a member of a cl ):o access a member using ob8ect name and a p (D) :o access a member using a pointer to the 31)5!at is $unction "rotot+"e ' :he function prototype describesng detailsfunction int such as number type of arguments and type of statement in the calling program and is of th ;+"e $unction<name6argument list)= 0g float !olume#int 9 float y$& 32)5!at is ctionaninline' $un An inline function is a function that is e9pa replaces the function call with the correspon :he inline functions are defined as Inlinefunction(header %

function body * 33) (ritesome situations 5!ere inline e:"ansion m / for functions returnings5itc!>orgotoae9ists!alues if loop a / for functions not returning !alues if a re / if functionstatic!ariablescontain / inlineiffunctionscursi!are re 3))5!at is a de$ault argument ' 1efault arguments assign a default !alue to t argument in the function call" 1efault !alues 0g < float amount#flperiod floatprinciplrate'G in"15$ 2unction call is >alue'amount#5GGG 6$& Qere it takes principle'5GGGP period'6 And default !alue for rate'G"15 >alue'amount#5GGG 6 G"34$ Passes an e9plicit !alue Gf G"34 to rate ;e must add default !alue from right to left 3*) t(!aare constant arguments ' keyword is const" :he Kualifier const tells t argument" :he compiler will generate an error declaration is significantpassargumentsonlybywhenreferencewe o eg< intconstcharstrlen#)p$& 3,) ?o5 t!e class is s"eci$ied ' Renerally class specification has two parts

/ class declaration .t describes the type and scope of its member / class function definition

.t describeshow the class functions are implemented ;!e general $orm is Classclass/name % pri!ate< !ariable declarations& function declaration& public<

!ariable declaration& function declaration& *&

3-) ?o5 to create an object ' Once the class hcasn becrenatedeclared !ariableswe of that t 0g<classname 9& ==memory for 9 is created

3.) ?o5 to access a class member ' ob8ect(name" function(name#actual arguments$ eg<9"getdata#1GG 65"5$& 3/) ?o5 t!e member $unctions are de$ined ' Memberunctionsf can be defined in two ways / outside the class definition

Member function can be defined by using scope Reneral format is

Returnclasstypename<<function(name#argument declaration$ % @ / .nside the class definition :his odmethof defining member function is to repl declaration by the actual function definition function

0g<class item % int a b & !oid getdata#int 9 int y$ % a'9& b'y& *& )0) (!at is static data member' Static !ariable are normally used to maintain 2eature<

/ .t is initiali@ed to @ero when the first ob permitted

/ only one copy of that memberssharediscreatedbyall for

the ob8ects / .t is only !isible within the class but it / type and scope of each static member !ariab / .t is stored separately rather than ob8ects 0g< staticountintiscount==cinitiali@ed to @ero when an o int classname<<count&==definition of static d

)1) (!at is static member $unction' A member function that is declared as static / A static functionstoonlycan otherha!e accesstatic member d same class

/ A static member function can be called usin classname <<function/name&

)2) ?o5 t!e objects are used as $unction argu :his can be done in two ways / A copyireof ob8ecttheentis passed to the argument / Only address of the ob8ects is transferred )3) (!at is called "ass b+ re$erence' .n this method address of an ob8ect is passed arguments" ))) %e$ineonst memberc .f a member function does not alter any data function as >oid mul#int int$const&

)*) %e$ine "ointers to member .t is possible to take the addresspointerof" a:hemembeadd a member can be obtained by applying the oper A class member pointer can be declared using 0g< class A % int m& public< !oid show# $& *& pointemberto m is defined as int A<<)ip'PA<<m& A<<)(Dpointer to member of A class PA<<m(Daddress of the m member of A class ),) (!en t!e de$erencing-ABisused'o"erator .t is used to access a member when we use poi )-)!en( t!e de$erencing o"erator #B is used' .t is used to access a member when the ob8ect ).) %e$ine local classes# +lasses can be defined and used inside a func .t canobaluse!ariablesgl and static !ariables decl automatic local !ariables" 0g& !oid test#int a$ %

OO" * class student % OOO *& student s1#a$& * )/) %e$ine constructor A constructor is a specialto initiali@ememberfunctiontheob8ewh special because its name is same as class nam of its associated class is consreatructsed".ttheis !cal members classofth

0g< +lassinteger % OO public< integer6 )=CCconstructor OOO * *0) %e$ine de$ault constructor :he constructor with no arguments is called d 0g< +lass integer

% int m n& Public< .nteger# $& OO"

*& integer<<integer#uctor$==default constr % m'G&n'G& * the statement integer a&

in!okes the default constructor *1) %e$ine "arameteri9ed constructor constructor with arguments is called paramete 0g& +lass integer % int m n& public<

integer#int 9 int y$ % m'9&n'y&

* :o in!oke parameteri@ed constructor we must pass constructor function when an ob8ect is declar

1",y calling the constructor e9plicitly eg< integer int1'integer#1G 1G$& 2",y callingimplicitlytheconstructor eg< .nteger int1#1G 1G$& *2) %e$ine de$ault argument constructor :he constructor with default arguments are ca 0g<

+omple9#float real float imag'G$& :he default !alue of the argument imag is G :he statement

comple9 a#6"G$ assign real'6"G and imag'G the statement

comple9 a#2"3 S"G$ assign real'2"3 and imag'S"G

*3) (!at is t!e ambiguit+ bet5een de$ault con constructor ' :he default argument constrguctorment canor nobe argumcalle called with no arguments it becomes a defaul class it cause ambiguity for a statement suc A<<A#int i'G$

*)) %e$ionstructoreco"+ A copy constructor is used to declare and ini reference to an ob8ect of the same class as a 0g< integer i2#i1$& would define the ob8ect i2 ati1the" same time i Another form of this statement is 0g< integer i2'i1& :he process of initiali@ingco"+throughinitiali@atio"copyco

**) %e$ine d+namic constructor Allocation of memory to ob8ects amicattimeconstructofth :he memory is allocated8E(o"eratorwiththe help of the 0g< +lass string % char )name& int length& public< string# $ % length'G& name'new charMlength B1N& * !oid main# $

% string name1#T-ouisH$ name3#-agrange$& *

*,) %e$inect const obje ;e can create constant ob8ect by using const 0g< +onst matri9 9#m n$&

*-) %e$ine destructor .t is used to destroy the ob8ects that ha!e b class name ildprecededsymbol#U$byt 0g& Uinteger#$ % * A destructor ne!er takes any arguments nor it from the program will in!oke it" ;hene!erne5operator is used to allocate memory in free that memory"

*.) %e$ine multi"le constructors 6constructor :he class that has different types of constru 0g< EincludeFiostream"hD EincludeFconio"hD

class integer % int m n& public<

integer# $constructor==defaul % m'G&n'G& * integer#int a int b$ ==parameteri@ed construc % m'a& n'b& * integer#Pi$ ==copy constructor % m'i"m& n'i"n& * !oid main#$ % integer i1& ==in!okes default constructor integer i2#45 66$&==in!okes parameteri@ed con integeri3#i2$& ==in!okes copy constructor

*/) (rite some s"ecial c!aracteristics o$ con A;hey should be declared in the public section A A A A A :hey are in!oked automatically when the ob8 :hey do not ha!e retuherefore ntypes andnothey!encanno!oi :hey cannot be inherited though a deri!ed :hey can ha!e default arguments +onstructors cannot be !irtual function

,0) ?o5 t!e objects are initiali9ed d+namical :o callteri@edparame constructor we should the pass ie for the constructor integer#int a int b$ it is in!oked by integer a#1G 17$ this !alue can be get during run time" i"e" int p K& cinDDpDDK& integer a#p K$&

,1)%e$ine Dunction'Inl .nline function is defined as a function defi replaced by the statements that define the fu general form is

inline(headerfunction %

function body *

,2)E:"lain return b+ re$erence 5it! an e:am"l A function can also return a reference" +onsi int P ma9# int P9 int Py$ % if#9Dy$ return 9& else return y& * Since the return typeon ofreturnsma9# refere$isincet Ptothe9 !alues$" :hen a function call such as ma9 # a on their !alues" :he statement ma9 # (1&a b$ ' is legalV1andto assignsifit V1isbto"larger otherwise

,3) (!at are Driend $unctions' (rite t!e s+nt A function that has access to the pri!ate mem class is called friend functions" :he general form is friend data/type function/name# $& 2riend sfunctionprecededi by the keyword WfriendX"

,))(rite some "ro"erties o$ $riend $unctions# / 2riend function is not in the scope of the cannot be called using the ob8ect of that cla / Lsuallyt itas hargumentsob8ec" / .t can be declared either in the public or / .t cannot access member names directly" .t dot membership operator with each member name

,*)(!at are irtual $unctions' Afunction Kualified by the W!irtualX keyword is called through a pointer class of the ob8 be used"

,,)(rite some o$ t!enctionsbasic rules $or irtual / >irtual functions must be member of some cl / :hey cannot be static members and they are / >irtual function in a base class must be de / Prototypes of base classe !ersderi!edon ofcl ass!irtu !ersions must be identical"

/ .f a !irtual function is defined in the bas deri!ed class"

,-) (!at are "ure irtual $unctions' (rite t! A pure !irtual functionse classis functhat ionhas declarenodef base class" .n such cases the compiler reKui

redeclare it as a pure !irtual function" A cl declarany ob8ect of its own" .t is also known a :he (nothingHTdo function is defined as follows< !irtual !oid display # $ 'G&

,.) (!at is "ol+mor"!ism' (!at are its t+"es' Polymorphism is the abilityatiton takemay e9hibitmorethand beha!iors in different" :he beha!ior depends types" :hey are / 2unction o!erloading / Operator o!erloading

,/) (!at is $unction o erloading' Gi e an e:a 2unctionngo!erloadimeanswe can use the same function a !ariety of different tasks" 0g< An o!erloaded add # $ function handles di i" ii" iii" int add# int a intentsb$&of==saddme functiontype wit int add# int a int b int c$& ==add func double add# int p double K$& ==add func different type

==2unction calls add #3 4$& ==uses prototype # i" $ add #3 es4 prototype5$&==us # ii" $

add #3 1G"G$& ==uses prototype # iii" $

-0) (!at is o"erator o erloading' +BB has the ability to pro!ide the operators mechanism of gi!ing such specialOperatormeaningso!erloato pro!ides a fle9ible option for the creation o

-1) 2ist out t!e o"erators t!at cannot be o e / +lass member access operator #" ")$ / Scope resolution operator #<<$

/ Si@e opi@eofrator$ # s / +onditional operator #Y<$

-2) (!at is t!e "ur"ose o$ using o"erator $un :o define an additional task to an operator to which the operatoryOperisatorppliedfunction":his whichisdon Operator functions are either member function return type classname(arglist<<$ operator #op % function body * whereturnis typethe type of fied!alueoprerationturned" by speci Op-operator beingopiso!eprloaeceded" by:hea keyword oper the function name"

-3) (rite at least $our rules $or O"erator o / Only the e9isting operators can be o!erload

/ :he o!erloadedustha!eoperatorleastm one operand tha defined data type"

/ :he basic meaning of the operator should no / O!erloaded operators follow the synta9 rule :hey cannot be o!erridden"

-)) ?o5 5ill +our+ Eo erloadFinar+ o"eratorGna using membe ;hen unary operators are o!erloaded using mem return no e9plicit !alues" ;hen binary operators are o!erloaded usingt" me Also the left hand side operand must be an ob

-*) ?o5 5ill +ou o erload Gnar+ and Finar+ o" ;hen unary operators are o!erloaded using fri #ob8ectthe ofrele!ant class$ ;hen binary operators two e9plicit arguments"

-,) ?o5 an o erloaded o"erator can be in o4ed .n case of Lnary operators o!erloaded operat op 8ectob/name or ob8ect/name op

.n case of binary operators it would be in!o Ob8ect " operator op#y$

where op is the o!erloaded operator and y is

--) ?o5 an o erloaded o"erator can be in o4ed

.n case ofators unaryo!erloadedoper operator can be in! Operator op #9$&

.n case of binary operators o!erloaded opera Operator op #9 y$

-.) 2ist out t!e o"erators t!at cannot be o e / Assignment operator ' / 2unction call operator # $ / Subscripting operator M N

/ +lass member access operator Z

-/) (!at is meant b+ casting o"erator and 5ri o"erator#

A casting operator is a function that satisfi / .t must be a class member"

/ .t must not specify a return type" / .t must not ha!e any arguments"

:he general form of o!erloaded casting operat operator type name # $

% OOO"" == function statements * .t is also known as con!ersion function"

.0):"lainE basic to class t+"e con ersion 5it! +on!ersion from basic data type to class type constructors does it" +onstructor takes a sin 0g< +on!ertingclassinttypetype to class time % int hrs mins& public< OOOO" :ime # int t$ ==constructor % hours' t=6G & ==t in minutes mins 't [ 6G& * *& +onstructor will be called automatically whil con!ersion is done automatically"

.1) E:"lainclass to basic t+"e con ersion 5it! an e Lsing :ype +asting operator con!ersion from done in the source class itself" 0g< !ector < < operator double# $ %

double sum'G& for#int .'G&.Fsi@e&.BB$ sum'sumB!M i N )uM i N & return sKrt # sum $ &

* :his function con!erts a !ector to the corres

.2) E:"lain one class to anot!er class con er +on!ersion from one class typebasictoanotherandbasisc type con!ersion" Qere constructor is used in used in source class" 0g< ob8\ ' ob8] ob8\ is the ob8ect of class \ and ob8] dis an into class \ type data and the con!erted !alu class and class \ is the destination class"

.3) (!at is meant b+ in!eritance' .nheritance is the process by rtieswhich ofob8ectsanother supports the concept of hierarchical classifi additional features to an e9isting class with

.)) (!at is meanteritance'b+single in! .f a single class is deri!ed from a single ba 0g< ,ase class 1eri!ed class

Qere class A is the base class from which the of class , hencepublicitinheritsmembersallof t," ,ut 1 can ,"

.*) (!at is multi"le in!eritance' .f a class is deri!ed from more than one base 0g< ,ase classes 1eri!ed class Qere class + isbasederi!edclassesfromA Ptwo,"

.,) (!at is !ierarc!ical in!eritance' .f a number of classes are deri!ed from a sin inheritance" 0g < Qierarchical classification of students A , A + ,

.-) (!at isl in!eritance'multle e .f a class is deri!ed from a class which in inheritance" :his process can be e9tended to 0g<

,ase class Rrand father .ntermediate ,ase class 2ather 1eri!ed+hildcass

..) (!at is !+brid in!eritance' .t is the combination of one or more types of Multile!el inheritance Multiple inheritance :he class result will ha!e both the multile!e Student Arts Engineering 7 e d i c a l CSE ECE Ci il A , + Student ;est &esult S"orts

./) (!at is meant b+ Abstract base class' A class that ser!es only as a base class from abstract base class are createdirtual" functionAbaseclassis class"

/0) (rite s!ort notes on irtual base class# A base class that is Kualified as !irtual in inheritance if the base classrit ismorenotthan!irtualone members of the base class" 2or a !irtual base regardless of number of inheritance paths bet

0g< Processing of studentsXsports resultsderi!e "theAssumeroll t student" +lass test is deri!ed from class Stu sports" As a !irtual base class As a !irtual base cla

/1)%e$ine Pol+mor"!ism' Polymorphism is stheonefeatureinterfacethattoallowbeused for Tone interface multiple methodsH" :his means group of related acti!ites":his helps usreduce to specify a general class of action"

/2)7ention some o$ t!e Se"arators used in Ha # $ / +ontain a list of parameters in method % * / +ontain the !alue of automatically init M N / 1eclaretypes" array

/ :erminate statements" " / Separate package name from sub packages"

/3)(!at is boolean data t+"e' ^a!a has simple type called boolean for logic !alues true or falsell" :hisrelat isonalthe operatorstypereturl reKuired by the conditional e9pression that g Student ;est &esult S"orts Synta9< boolean !ariablename&

/))?o5 d+namic initiali9ationja a' o$ ariables is ^a!a allows !ariables to be initiali@ed dynam !ariable is declared" double a' 3"G b'4"G double c'Math"sKrt# a ) a B b ) b$& here TcH is initiali@ed dynamically to the le

/*)(!atis meant b+ (idening con ersion' ;hen one type of data is assigned to another place if the following conditions are met " :he two types are compatible" :he destination type is larger than the sourc 2or e9ample the int type is always large enou

/,)(!at is meant b+ narro5ing con ersion'

;e are e9plicitly making the !alue narrower s is not performed":o automaticallycreatecon!ersion between must use a cast" A cast is simply an e9plicit S+nta:<#target(type$!alue target(type / the desired type to con!ert the spe

/-)State ;+"e Promotion &ules' AlltebyP short !alues are promoted to int" if o promoted to long" .f one operand is a float o any one operand is double the result is doub byte shortloat longdoublef

/.)?o5 to create a one dimensional arra+s' A one dimensional array is a list of liked ty !ariable of desired data type" S+nta:<type(nameMN&!ar

//)?ere-name aris setn4to5it!nullan# ;oactual>li "!+sical a allocate using ne5#

bb< array(!ar'new typeMsi@eN&

100)(!at is t!e use o$ ternar+ o"erator' :he ternary operator(th(nlse statementsreplacesif" S+nta:<e9pression1Ye9pression2<e9pression3 0g< ratio' '' GdenomY< num = denom& .f e9pression1 is true then e9pression2 is e

:he result of Y operation is that of the e9pr

101)(rite do5n t!e s+nta: o$ s5itc! statement Switch#e9pression$% casee1<!alu ==statement seKuence break&

case !alue2< ==statement seKuence break&

" " " case !alueJ< ==statement seKuence break&

default< ==default statement seKuence *

102)(!at are t!e iteration statements used in (!ile<repeats a statementitscontrollingorblock e9pressionwhile i Synta9< while#condition$%

==body of loop * do-5!ile<09ecutes its body atleast once Synta9< do% ==body of loop *while#condition$& $or< consists of three portions initiali@ation Synta9< ation conditon terminationfor#initiali@"$% ==body *

103)(!at is t!e di$$erence bet5een brea4 E co ,reak< ;e can force immediate termination of e9pression P any remaininga codebrakins tatementhebody io in a loop the loop is terminated P the progr the loop"

+ontinue< useful to force early termination" remainderodeofintheitXsc body for this particular i

10))(!at are t!e uses o$ brea4 statements' 1".t terminates a statement seKuence in switc 2".t can be used to e9it a loop"

3"it can be used as a ci!ili@ed form of goto"

10*)%e$ine Constructors'

A constructor initiali@es an ob8ect immediate which it resides P is syntactically similar t automatically called immediatthelynewafteroperatorthe obc S+nta:<cl(!arss' new classname# $&

10,)%e$ine "arameteri9ed Constructors' :o construct an ob8ect of !arious dimensions 0g< ,o9 mybo91' new ,o9#1G 2G 15$& ,o9 mybo91' new ,o9#6 15$&

10-)(!at is t!e use o$ ;!is 4e+5ord' :his is always a reference to the ob8ect on w inside any method to refer to the current ob8 ,o9#double w double h double d$% :his" width ' w& :his" height' h& :histh" dep'd& *

10.)%e$ine Garbage collection' :he techniKue used to handle the deal locatio e9ists that ob8ect is assumed to be no longe be reclaimedlection"Rarbageoccurscol sporadically during

10/)(!at is t!e use o$ $inali9e6) met!od'

.f an ob8ect (is8a!aholdingresourcesomesuchnon as a file han which might be freedd "bef:orehandlesituationob8esucht ^a!aisdestpro mechanism called finali@ation" ,y using final when an ob8ects 8ust about to reclaimed by th S+nta:<protected !oid finali@e#$ % ==finali@ation code *

110)%e$ine 7et!od o erloading' .n ^a!a it is possible to define two or metho long as the parameter declarations are differ o!erloadedprocessPtheis referred to as method o!erl !oid test#int a$% System"out"println#Ta< T Ba$& * !oid test#double a$% System"out"println#Ta< T Ba$& * !oid test#int a int b$% System"out"println#Ta and b< T Ba BH T Bb$& *

111)(!at are t!eargumentdi$$erentPassing'5a+so$ +all(by(!alue< :his method copies the !alue of an subroutine" :herefore changes made to the par argument used to call it"

+all(by(Reference<method.n this areference to an argument this subroutine this reference is used to ac means that changes made to the parameouterinewill"

112)7ention some o$ t!e restrictions 5!ile us :hey can call other static methods" :hey must only access the static data" :hey cannott!isorreferu"erany wayto"

113)(!at is t!e use o$ $inal 4e+5ord' .t is useditstocontpre!entnts from being modified" .t initiali@e a final !ariable when it is declar 0g<$inalint 2.-0/J0;'1&

11))?o5 to call a Su"er class constructors' A subclass can call a constructorclassby usemethofd thedefi ofsu"er# Super#parameter(list$& Parameter list/any parameters needed by the c be the first statement e9ecuted inside a subc

11*)(!at areu"ert!e 4e+5ord'useso$ s 1"Lsing super we can call Super class constru 2"it acts like this e9cept that it always re

11,)%e$ine 7et!od o erriding' ;hen a method in a subclaypesignshasturethe asame methoname said to o!erride the method in the superclass subclass it will always refer to the !ersion class A% OO" >oid show#$% System"out"println#TSuper classH$ * class , e9tends A% OO" >oid show#$% System"out"println#Tsub classH$ * class o!erride% , sub ' new ,# $& Sub" show# $& *

11-)%e$ine %+namic 7et!od %is"atc!' 1ynamic Method 1ispatch is therriddenmechanismfunctionbyw resol!ed at run time rather than compile tim means of 1ynamic Method 1ispatch" Principle< A super class reference !ariable c resol!e!erriddencallsto methods at run time" when ah

super class reference 8a!a determines which type of the ob8ect being referredthetob8ecat thebeit referred to that determines which !ersion of

11.)(!at are t!e uses o$ $inal 4e+5ord' 1" 2" 3" to create the eKui!alent of named constant :o Pre!ent o!erriding :o pre!ent inheritance"

11/)?o5e$ineto da Pac4age' .nclude package statement as the first statem defines a name space in which classes are sto S+nta:<package pkg& Pkg / name of the package" ;e can create a hierarchyeparate ofeachlassespackage"2ornametha by use of a period" S+nta:<package pkg1Mpkg2M"pkg3NN&

120)?o5 to im"ort "ac4ages' ^a!a includes the import statements to bring import staterimmediatelyentsoccu following the package definitions" S+nta:<import pkg1M"pkg2N"# class name_ )$& Pkg1 /name of the :op le!el package" pkg2 /name of the subordinate package inside

dot"

121)(ritedo5n t!e s+nta: $or de$ining Inter$ace' An interface is defined similar to a class S+nta:<access interfacename% Return type(name1#parametermethod list$& Return type(name2#parametermethod list$& type V!arname1final ' !alue& type V!arname1final ' !alue&

==O Return type(nameJ#parametermethod list$& type V!arname1final ' !alue&

122)(!at are t!e ste"s to be $ollo5ed 5!ile i :o implement an interface include the implem methodsefined by the interface" S+nta:<access class classnameMe9tends super cla .mplements interfaceM interfaceONN% ==class body * access / either public or not used"

123)(rite do5n t!e $undamentals o$ E:ce"tion

A 8a!a e9ceptiondescribesisan ob8ectane9ceptionalthat condit of code" ;hen an e9ceptional condition arises thrown in the method that caused error" ^a!a 09ception handling s<try catch throw ismanagedthrough fi throws and finally" S+nta:<try% ==block of code to monitor errors * catch#09pression type1 e9ob$% ==e9ception handler for 09ception type1 * catch#09pression type1 e9ob$% ==e9ception handler for 09ception type1 * ==O" finally% ==blockfcode to be e9ecuted before try block end *

12))%e$ine 7ultit!readed Programming' A Multithreaded program contains two or more a program is called a thread e9ecution Andeach" thread:hus threading is a speciali@ed form of multitaski

12*)7ention some o$ t!e met!ods de$ined b+ ;!

7et!od 7eaning getJame Obtain a threadXs name getPriority Obtain a threadXs priority isAli!e 1eterminenningif a thread is still ru 8oin wait for a thread to terminate

run 0ntry point for the thread sleep Suspend a thread for a period of time"

12,)(!at are t!e t5o 5a+s $or creating a ;!re ,y implementing the runnable interface" +lass Jewthread implements Runnable ,y 09tendingthe :hread class +lass Jewthread e9tends :hread

Part-F 1#(!at are t!e Deatures o$ Oo"Is E !o5 are t! A A A A A Ob8ects" +lasses" 1ata abstraction and 0ncapsulation" .nheritance" Polymorphism"

1ynamic binding" A Messageing"pass

2# E:"lain about inline $unction' An inline function is a function thatcompilerise9pa replaces the function call with the correspon as

Inlinefunction(header % function body * :he situations where inline e9pansion may not A A A for functions returnings5itc!>orgotoae9ists!alues if loop a for functions not returning !alues if a re if funcstaticion!ariablescontain

Afinlinefunctions are recursi!e

3# E:"lain Dunction O erloading' 2unction o!erloading means we can use the sam a !ariety of different tasks" 0g< An o!erloaded add # $ asfunctionshown belowhandles" di = i!" !" !i" 1eclarations int add# int a int b$& ==add function wi int add# int a int b int c$& ==add funct double add# int p double K$& ==add funct

different type ==2unction calls

i" ii" iii"

add #3 4$& add #3 4 5$& add #3 1G"G$&

)# E:"lain about O"erator O erloading' +BB has the ability to pro!ide the operators mechanism of gi!ings tosuchan soperatorcialmeaniisknowng as pro!ides a fle9ible option for the creation o :he operators that cannot be o!erloaded are" A A +lass member access operator #" ")$ Scope resolution operator #<<$

ASi@e operator # si@e of $ A +onditional operator #Y<$ :he purpose of using operator function is to specify what it means in relation to the clas Operatorunctionf which describes the task" Opera friend functions"

:he general form is return type classname(arglist<<$ operator #op % function body * whereturnis typethe type of !aluetionreturned" by speci Op-operator beingopiso!eprloaeceded" by:hea keyword oper

the function name" :he rules for Operator o!e A A Only the e9isting operators can be o!erload :he o!erloaded operatorthatmustis ha!eofuserat least defined data type"

A A

:he basic meaning of the operator should no O!erloaded operators follow the synta9 rule :hey cannot be o!erridden"

*# E:"lain o erloading Gnar+ E Finar+ o"erato ;hen unaoperyators are o!erloaded using member fu return no e9plicit !alues" ;hen binary operators are o!erloaded using me Also the left hand sideftheoperandrele!antmustclassbean" ob ;hen unary operators are o!erloaded using fri #ob8ect of the rele!ant class$ ;hen binary operators are o!erloaded using fr operatorin!okedcanbeusing member functions as follo .n case of Lnary operators o!erloaded operat ob8ect/name op .n case of binary operators it would be in!o Ob8ect " operator op#y$ where op is the do!erloadedyisthe argumentoperator" an :he o!erloaded operator can be in!oked using .n case of unary operators o!erloaded operat Operator op #9$& .n case of binary operators o!erloaded opera

Operator op #9 y$ :he operators that cannot be o!erloaded using A A A A Assignment operator ' 2unction call operator # $ Subscripting operator M N +lass member access operator Z

,# E:"lain about ;+"e con ersions' :he three types of data con!ersion are i"n!ersion+o from basic type to class type" ii" iii" +on!ersion from class type to basic type" +on!ersion from one class type to anothe A casting operator is a function that satisfi

A .t must be a class member" A .tnotmustspecify a return type" A .t must not ha!e any arguments" :he general form of o!erloaded casting operat operator type name # $

% OOO"" == function statements * .t is also known as con!ersion function" i" ,asic to class type con!ersion

+on!ersionombasicf data type to class type can be does it" +onstructor takes a single argument 0g< +on!erting int type to class type class time % int hrs mins& public< OOOO" :ime #=constructorintt$ % hours' t=6G & ==t in minutes mins 't [ 6G& * *& +onstructor will be called automatically whil automatically" ii" ,asic type con!ersion with an e9ample" Lsing :ype +astingfromperator classtocon!ersionbasictype con done in the source class itself" 0g< !ector < < operator double# $ % double sum'G& for#int .'G&.Fsi@e&.BB$ sum'sumB!M i N )uM i N & return sKrt # sum $ &

* :his function con!ertsspondinga!escalartortomagnitudethecorre" iii" One class to another class con!ersion wi +on!ersion from one class type to another is type con!ersion" Qere constructoringoperatorisusedfuinc used in source class" 0g< ob8\ ' ob8] ob8\ is the ob8ect of class \ and ob8] is an into class \ type data and the con!ertedource!alu class and class \ is the destination class"

-# E:"lain in!eritance' .nheritance is the process by which ob8ects o supports the concept of hierarchicalusabi ityclassifi";e additional features to an e9isting class with i" single inheritance .f a single class is deri!ed from a single ba 0g< ,ase class 1eri!ed class Qereclass A is the base class from which the cl of class , hence it inherits all the public m ,"

ii" multiple inheritance .f a class is deri!edonebasefromclass moreitthanis called mu 0g< ,ase classes 1eri!ed class

Qere class + is deri!ed from two base classes iii" Qierarchical inheritance .f a number of classes are deri!ed from a sin inheritance" 0g < Qierarchical classification of students A , A + , Student Arts Engineering 7 e d i c a l CSE ECE Ci il i!"Multile!el inheritance .f a class is deri!ed from a class whichtile!elin inheritance" :his process can be e9tended to 0g< ,ase class Rrand father .ntermediate ,ase class 2ather 1eri!ed class +hild !" Qybrid inheritance .t is the combination of one or ha!emore bothtypestheof multile!el and multiple inheritances" Multile!el

inheritance Multiple inheritance

.# %e$ine constructor A constructor is a special member function wh special becauseas itsclassnamenameis" same:he constructor i of its associated class is created" .t is cal members of the class

0g< +lassinteger % OO public< integer6 )=CCconstructor OOO * A F C Student ;est &esult S"orts :he different types of constructor are

i" default constructor :he constructor with no arguments is called d 0g<

+lass integer % int m n& Public< .nteger# $& OO"

*& integer<<integer# $==default constructor % m'G&n'G * the statement integer a&

in!okes the default constructor ii" parameteri@ed constructor

constructor with arguments is called paramete 0g&

+lass integer % int m n& public<

integer#int 9 int y$ % m'9&n'y&

* :o in!oke parameteri@edctorwemustconstrupass the initial !a constructor function when an ob8ect is declar 1",y calling the constructor e9plicitly eg<

integer int1'integer#1G 1G$& 2",y calling the constructor implicitly eg<

.ntegerint1#1G 1G$& iii" 1efault argument constructor :he constructor with default arguments are ca 0g<

+omple9#float real float imag'G$& :he default !alue of the argument imag is G :he statement

comple9 a#6"G$ assign real'6imag'G"G and the statement comple9 a#2"3 S"G$

assign real'2"3 and imag'S"G i!" +opy constructor

A copy constructor is used to declare and ini reference to an ob8ect of the same class as a 0g< integer#i1$& i2 would define the ob8ect i2 at the same time i Another form of this statement is 0g< integer i2'i1& :he process of initiali@ingco"+throughinitiali@atio"copyco !"1ynamic constructor All ocatinof memory to ob8ects at time of their c :he memory is allocated8E(o"eratorwiththe help of the 0g< +lass string % char )name& int length& public< string# $ % length'G& name'new charMlength B1N& * !oid $main# % string name1#T-ouisH$ name3#-agrange$&

* use delete to free that memory"

/# E:"lain about 7ulti"le constructors 6const :he class that has different types of constru 0g<

EincludeFiostream"hD EincludeFconio"hD class integer

% int m n& public<

integer# $ ==default constructor % m'G&n'G& * integer#int a int b$ ==parameteri@ed construc % m'a& n'b& * integer#Pi$ ==copy constructor % m'i"m&

n'i"n& * !oid main#$ % integer i1& ==in!uctorkes default constr integer i2#45 66$&==in!okes parameteri@ed con integer i3#i2$& ==in!okes copy constructor

* :he special characteristics of constructor ar A;hey should be declared in the public section A A A A A :hey are in!oked automeatedically when the ob8 :hey do not ha!e return types not e!en !oi :hey cannot be inherited though a deri!ed :hey can ha!e default arguments +onstructors cannot be !irtual function

10#:"lainE irtual $unctions A function Kualified by the W!irtualX keyword is called through a pointer class of the ob8 be used"

:he rulesunctionsfor!irtualare f / >irtual functions must be member of some cl / :hey cannot be static members and they are / >irtual function in a base class must be de

/ Prototypes of base classll !ersionthederi!edofa class!irtu identical" / .f a !irtual function is defined in the bas Pure !irtual functions A pure !irtual function is a functionrelati!edeclaret base class" .n such cases the compiler reKui redeclare it as a pure !irtual function" A cl declare any ob8ectsalsoofknownits ownas"TdonothingH.t func

:he (nothingHTdo function is defined as follows< !irtual !oid display # $ 'G&

11# E:"lain t!e $eatures o$ Ha a' A A A A +ompiled and .nterpreted Platform(.ndependent and portable Ob8ect oriented Robust and Secure

A istributed1 A A A A 2amiliar simple and small Multithreaded and .nteracti!e Qigh Performance 1ynamic and 09tensible

12# %escribe t!e structure o$ Ha a "rogram' A 1ocumentation section

Package statement A A A A .mport statements .nterface statements ss+ladefinitions Main method class

13# E:"lain about In!eritance in Ha a' A A A A A 1efining a subclass Subclass constructor Single .nheritance Multile!el .nheritance Qierarchical .nheritance 0g<

+lass A % ((((((((( ((((((((( * class , e9tends A % ((---( ((((((((( *

class + e9tends , % ((((((( (((((((( *

1)# E:"lain about Inter$aces in Ha a' ^a!a does not support multiple inheritances" A A A A 1efining .nterfaces 09tending .nterfaces .mplementing .nterfaces cessingAc .nterface !ariables 0g <

.nterface Area % final static flaot pi'3"14f& float compute#float 9 float y$&

1*# E:"lain about Pac4ages' Packages are 8a!aXs way of grouping !ariety o Packages act asssescontainers for cla

A ^a!a AP. Packages

Lsing System packages A A A 0g< Package p1& Public class A % public !oid display#$ % System"out println#T+lass AH$& * * +reating Packages Accessing a package Lsing a package

1,# E:"lain about ;!reads in Ha a' A threadramis thatproghas a single flow of control A A +reating threads 09tending the thread class 0g<

+lass Mythread e9tends :hread % (((((( ((((((

* A Lsing Runnable .nterface 0g<

+lass My:hread implements Runnable % ((((((( ((((((( * A Stopping and ,locking a thread

1-# E:"lain about Strings in Ha a' A Strings can be created using / String class

String s' new String#TQelloH$& / String,uffer class

String,uffer s' new String,uffer#TQelloH$& A A String arrays String methods

1.# E:"lain about ;!read li$ec+cle' A A A Jewborn state Runnable state Running state

,locked state A 1ead state

1/# E:"lain about E:ce"tion !andling in Ha a' A A A A 0g< +lass A % public dstaticmain #String!oi argsMN$ % int a'1G& int b'5& int c'5& int 9 y& try 09ceptions Synta9 of 09ceptions handling state Multiple catch statements Lsing finally statement

% 9'a=#b(c$& * catch#Arithmetic09ception e$ %

System"out"println#T1i!ision by @eroH$& * y'a=bBc& System"out"println#Ty'HBy$& * *

20# E:"lain about A""let 2i$ec+cle' A A A A A .nitiali@ation state Running state .dle state or stopped state 1ead state 1isplay state

21# ?o5 A""lets are "re"ared and e:ecuted' A ;riting Applets 0g< .mport 8a!a"awt")& .mport 8a!a"applet")& Public class A e9tends Applet % public !oid paint# Rraphics g$ %

g"drawString#TQelloH 1G 1GG$& * * A A ,uilding Applet code 1esigning a web page FhtmlD

FtitleDAppletF=titleD FbodyD

Fapplet code' A"class width'4GG height'2GG F= F=bodyD

F=htmlD A A A Running the Applet Lsing applet!iewer Lsing web browser

22# E:"lainutJisibilit+abo Controls' A A A A A Public access 2riendly access Protected access Pri!ate access Pri!ate protected access

23# E:"lain about 7et!ods o erriding and met!

Methods that ha!e same name but different par definitions is called Method o!erloading"

0g< class Room % int width& int length&

Room#int 9 int y$ == +onstructor % length' 9& width ' y&

* Room#int 9$ % length'breadth'9& * * ;hen a method is called the method defined in e9ecuted instead of the one in the superclass" 0g<

class superclass % !oid methodsuper#$

% System"outI`su""rintln#erclassI`$& method * * class subclass e9tends superclass % !oid methodsuper#$ % System"outI`o!e"printlridiofn#g superclassI`$&method * * class o!erride % public static !oid main#String argsMN$ % subclass sb'new subclass#$& sb"methodsuper#$&

* *

2) E:"lain about o"erators in Ha a' A A Arithmetic operators .nteger arithmetic

Real arithmetic A Mi9ed mode arithmetic

ARelational operators

A A A A A A A A

-ogical operators Assignment operators .ncrement and 1ecrement operators +onditional Operator ,itwise operator Special operators .nstanceof operator 1ot operator

2* E:"lain about Constructors in Ha a' +onstructorsableanenob8ect to initiali@e itself whe 0g< class Rect

% int width& int length&

Rect#int 9 int y$ == +onstructor % length

' 9& width ' y&

int rectArea#$ % return#length )width$&* *

2,# E:"lain t!e arious Ha a to4ens' A A A A A A ^a!a character se Ceywords .dentifiers -iterals Operators Separators

2-# ?o5 5ill +ou im"lement a Ha a "rogram' A +reating the ^a!a program class sample % public static !oid main#String argsMN$ % System"out"println#TQelloH$& * * Sa!e the program as sample"8a!a

A +ompiling the program :he program is compiled using the statement a class file named sample"class"

^a!ac sample"8a!a A Running the program ^a!a sample

:his statement will e9ecute the program and d

2.# (!at$eaturesaret!e o$ sim"le Ha a "rogram' A +lass declaration A A A 0g Opening brace Main -ine Output line

class sample == +lass declaration % == Opening brace

public static !oid main#String argsMN$ == Mai % System"out"println#TQelloH$& == Output line

* */

Potrebbero piacerti anche