CHPTR 1 CMPTR

You might also like

Download as pdf
Download as pdf
You are on page 1of 13
UNIT I [PLES OF OBJECT ORIENTED PROGRAMMING level languages, High level languages (advantages and disadvantages), erpreter, Types of High level languages, Structure Oriented Programming, d programming and Object Oriented programming, Features of Object ming, Difference between Procedural Oriented programming and Object ramming, All the four principles of OOP viz. Data abstraction, Inheritance, Encapsulation with real life examples ter is an electronic device that accepts instructions in a specific language. it is very difficult to establish communication between the user and the uter if he/she is not aware of computer language. This is the reason why computer language is very essential for working on the computer. S OF COMPUTER LANGUAGES somputer languages are basically categorised into two levels. They are: ‘Computer languages pM eee High Level Languages ow Level Languages Jow level languages are the type of computer languages in which the ter recognizes the instructions, without conversion into any other form. “are sort of cryptic languages which are not directly understood by the These type of languages were used in the early computers when only the were able to code the instructions. The low level languages are further into two types: Level Language n of computer language in which instructions are coded in terms (bits), ie., in the form of zeroes and ones (0's and 1's). This nstructions is also called the machine code or the object code. eo “3 The only advantage of this 2. High Level Language fhe machine code is directly ‘To overcome the disadvantages of low level languages, the e% Developers) developed another category of languages, which are ref ue at as the High Level Languages (HLL). These languages allow the user to ‘user must be aware of the intera) | the instructions in simple English phrases or sentences. It also uses common structure of the computer for / English words and mathematical symbols. Thus, it makes the instructions { coding instructions; and so it is known, easier to understand in the user's native language. It allows a user to write the ‘as a machine dependent language. instructions, even if he is not aware of the hardware architecture of the computer. e The programming style and context is comparatively easier to learn. The entire code focuses on the specific program to be created. BASIC, C/C++, Java and Python are some popular examples of high level languages. % Advantages of High Level language: are coded in terms of mnemonics and is known as an assembly level language. The + It is a machine independent language. form of the instructions, used for writing + The instructions can be written using English words or phrases, ae the numeric codes of the instructions that are * It is easier to understand and develop the program logic, for execution. The instructions in assembly level + The error detection and correction is easier. Disadoantages of High Level language: * It requires a translator to convert the source code (program) into machine code. ‘ - CODES % oF * The machine code of high level instructions might be less efficient than the 3B machine code generated from assembly level instructions, B One of the major disadvantages of the High level language is that the machine ie cannot understand this language directly (a machine understands only machine ce level language). Hence, we need to convert the instructions written in high level aF language into their equivalent instructions, in machine level language, so that they can be operated upon by the CPU. The translators /language processors used EF to perform above mentioned task, are referred to as Compilers and. Interpreters, Let us understand the functions of these translators, assembly level language are not directly understood Oris required to convert the instructions coded fo its equivalent machine code which is known COMPILER AND INTERPRETER Aprogram in high level language needs to be converted into machine code (binary code) so that the computer can understand the instructions for processing. If the Program contains any error then it must be corrected for successful execution. ‘The conversion of high-level language (source code) to machine level *, MLL (binary code) can be done in two ways; either by using a Compiler or an Interpreter. 4 5 A software that accepts the whole program written high level converts it into its equivalent program in machine level language, is the compiler, a ‘The program, which the compiler uses for conversion, is know pregran or source code. The program converted into the machi 4s known as the object program or object code. Be es ~ compiter igh Level Langueo® es Peach high level programming ne for more than one high level I is designed A compiler high level language ble of trans! would requi compiler is capab may have more than one com ft nich converts the ) The software whic “ann neh et (ag ‘other gu eS ee et ips min Mn Asam aka iain mamma! hy set, degrasng ae a inom a eo On ope oon his process of orrecting errors is easier bu a sare espretr is generally used in micro computers. It helps the ase ee erm and correct them before the control. moves #9 se Cnpcs andnerpreters ae basally system softwares statement. Compilers and inte also known as the Ue ated comparatively faster than the interpreter but becomes dificult to correct errors since it displays all the errors togel [Ste ee ees prepa Dire btwn Cpe cad’ sa ea 1. It converts the source pro the object program one line 1. Ttconverts the whole source program into the object program at once. 21 ‘displays the errors for the 2. It displays the errors, hole Program together, afer the time and only after deb ‘compilation, error the control goes 10 | TYPES OF HIGH Ley EL LANGUAGES High level languages a |. Structure Oriented Programming Language Structure Oriented language uses a modit quality and the development time of the logical structures like the structure block, structure of subroutine examples of structure lar approach to improve the clarity, Programming steps. It uses various of selective control flow, structure of "sor functions etc. ALGOL and PASCAL are oriented programming languages, 2. Procedure Oriented Programming Language ‘The procedure oriented approach allows the users to develop thelr log by using ‘number of functions that would enhance the program's productivity. ere ant onal programming using high level languages such as BASIC, COBOL, FORTRAN and C are commonly known as Procedure Oriented Programming (POP) languages. Here, a sample flow diagram s illustrated to depict the procedural Programming approach: a) Procedure Oriented Programming (POP) basically consists of a list of iRstructions for the computer to follow and these are organized into groups, Known as fivictions. We normally use a flow chart to organize these actions andl represent the flow of control from one function to another. In Procedure Oriented Programming, most of the functions share global data and this data moves more openly around the system from one function to the other. When we deal with a program containi items are globally used by all the functions, however, its own local data to deal with logical situations, The its function in POP can be illustrated as: ‘ing many functions, important data function may contain organisation of data and ‘The different Object Oriented Programming languages commonly being used are C++, Java, Python, Smalltalk, Ruby, Eiffel, ete WY jer to make at throughout the ge in the ay need 10 yes. This may any cha ata V reschedule the associ she program lOgic ‘An Object Oriented Programming (OOP) C++ ‘the normal sequent e ‘approach, which allows the data to be “within Jav: z dure Oriented Programming | Stipulated program area. i also provides the reusabilty 2 Java Caracestinof Procedre One lle deton adie og which eats © ows python functions (logical "more emphasis on data + Emphas ; Data values can keep floating from Features of Object Oriented Programming (OOP) + ruses top down approach of program Some of the features of Object Oriented Programming are listed below ted Programming (POP) * It gives importance to the data items rather than the functions wl the functions, You may requige + Itmakes the complete program/ problem simpler by dividing it into a number Limitations of Procedure Ori «As data values are global to * The concept of data hiding enhances the security in programs 3, OBJECT ORIENTED PROGRAMMING (OOP) * It is highly beneficial to solve complex problems. Procedure Oriented Programming basically consists of an organised itrucons known as futon. Normally flow charts are used to oy Differences between Procedural Oriented Programming (POP) and inctuctons and guide te movement of contol from. one funcHSaia Object Oriented Programming (OOP) Most of the functions share global data that flows freely throughout the: Now, you have leamt that both are programming processes where OOP stands sat psi for ‘Object Oriented Programming’ and POP stands for ‘Procedure Oriented een Si Pracani OR Programming’, They are different types of high-level programming languages ic. ea eae wg ae 3 With different approaches. Some of the differences between them art mentioned is an approach to standardize the programs by Pier memory area for both the data and the functions. It does not allow flow freely from one function to another. In this system, the complete prol aes aaa a ne desomposed into a numberof entities called the cc's. Each object inc |. The cmphasis is put on the function 1. The emphasis spt onthe data rather of data items and related functions. The data values of an object are a oes Ea than the functions. pie Rita bes ected 4 : 2. Wallows data toflow freely throughout 2. The data is restricted, to be used in a associated with that object. The resident Me ‘ never be handled by the Program specific program area, ; external functions. 7 . 3. follows, top-down programming 3. 1 follows bottomiop_programming In this way the data are : oe svt aes ee protected and secure from i 3 being troubled by external Sources. This feature allows object oriented approach to bea powerful tool in programming. The organisation of dat, and functions in Object k Oriented amming te ‘whereas behaviour refers to the purpose of its use o its (COP) can beillustrated as. 4 PS KEYWORDS RELATED TO OBJECT ORIENTED PROGRAMMING : * Object: It is a unique entity, which contains data and functions — (characteristics and behaviour) together in an Object Oriented Programming | (COP) Language. sa sh ined as an of 7 we compare axe O1 teristics and members and q spectively, ‘ombined features of both the classes. The class that ge lass is known as tie Base class or the Super class Base class is known as ts inherited to another The class that inherits from a Derived class O« the Subclass OF Target Let us take an example of a class ‘Animal’ which can be broadly classified into ‘Camivores’ (flesh eating animals) and ‘Herbivores’ (plants eating animales So, you will find that some of the « is also referred to as @ characteristics or properties of the class ‘Animal’ will be inherited by the classes Camnivores and Herbivores similar type g ttributes and comment Each 1 ORIENTED PROGRAMMING (@6 c Basic PRINCIPLES OF OBJECT UX. following base e con ore : + Inher | : + Data Abstracto + Encap ' «Polymorphism | / { | | Data Abstraction epee 24 | In real life situations, you mig} of the | eee re do not require to know the details of th During inheritance, the elements of the base class are shared by the derived nologies to operate any system class. As a result, it may happen that the elements performing a specific task in f ple, a digital camera is used to capture a the base class can be used to perform another task in derived class, This feature For eample fs called Reusabilty photograph. Itsimply provides an and switches to control the operations needed to take the photograph. In fact, these buttons make working so eay that anybody could operate the camera, even though he/she may not be aware of the technology. Have you ever thought of how does the camera manage to take: ‘oF what mechanism is followed in the internal part of the camera? You may not be able to answer technology used inside the camera. nacnansannoncang share some common properties of one} done by extending a class into another ‘The term Inheritance means to link and ‘class with the other class. This can be Class and using thus using both it Polymorphism You know that a single wi yord can have many meanin, such questions bes ou are y gs. n evextions boos Similarly, an operation may show an entirely different Sa, you my sy tat we use cnly the SDSROEGRI behaviour for a different set of data and environment. essential features of the So an Let us take an example of the English word ‘duck’ | een oe oe a The word ‘duck’ defines a water bird with a broad ! even pea bil short legs and webbed feet whereas, the same word : may be noted thatthe abstraction of {_Purbose of the SBE en 7 an object depends upon the are of applications, Inheritance You might have stu; ’ idied the term 4 parsmission of genetically based cha We inherit thousands of character who in tur, had inherited th Similarly, Heredity’ in biology, which’ ‘acteristics from parents to the | ‘stics (inheritable features) from Ot 8 clas acquires gn, thei parents, and $0 on ie PtOPetties from another class: P “sting class. The new class 4 New class from the X O sent pee by deriving With the reference to the above examples, you can notice that the duck’ is used for two different purposes. Similarly, you can fing examples in real life situations also. With reference to Object Oriented Programming, if the Volume( ), then you can calculate the volume of different geomet figures viz. a cube, a cuboid, a sphere, a cylinder by using different pa as shown below With reference to the above context, it could be inferred that the state and behaviour are encapsulated in an Object Oriented Programming to prevent their isolation from each other. Thus, encapsulation is helpful in Object Oriented Programming in the following ways: (a) The source code of an object could be maintained independently (b) The object maintains the privacy of the data members, However, the changes that take place in the methods do not affect the other object. Benefits of Object Oriented Programming There are many reasons of preferring Object Oriented Programming over Procedure Oriented Programming. Some of them are mentioned below: * The reusability of the program code is enhanced. + The software quality and performance are improved. + Modularity is achieved ‘Data abstraction makes the software easier to handle. ‘+ Software for complex tasks can easily be developed. Limitations of Object Oriented Programming ae ; | _Even though, OOP languages are preferred in solving problems ranging from mE Eee re ot meee: Se ere eee gue Wr as oe Co Os [Sep comp the a = ict, dikes eae of data oes ‘one object to another. The data and '* Object Oriented Programming languages require intensive testing, processes. are wray in an such that the data ace : (oe een eee aa the associated functions, ae 4 . Sa problems is more time consuming as compared to Procedure Orient Thus, we can say that the data is kept hidden and cannot be accessed Eanes outside the object, although it is available in the same program. The ieraon ot Pate ie ne ie Prog Te Polymorphism is one of the Object Oriented Programming (OOP) pi that allows the user to use a function for multiple purposes. It is imp by using fivictio overincting. Thus, function overloading is a technique ‘number of functions, with the same name, having different parameters. In the illustration shown above, three functions are defined with the same name ‘volume’. Hence, they are overloaded. The execution of these functions will depend upon the data types and number of parameters CC WwW—_—_———————E__ ‘TEREREISED 1. Fill in the blanks: I. An act of using essential features without including the background details is called 2. in an Object Oriented Programming, the importance is 6¥88 12 together as a single unit is called 3. Wrapping of data and functions has a unique identity which contains some 4 languages BOL gaming languages? ves on the: >ughout the Prog 4.An that needs to bee Characteristics and behaviour npiler‘Interpreter) is 1. The objects may communicate with each other through ine code that « @. In POP. the global data are loosely attached to the Z the spect code 8 rr procesr by which » class ecules the properties from another case Hat i of Object Oriented Programming a - fo) Name any to basic Prine ii) Encapsulation & In Object Oriented programming, using a function for many purposes is termed Decne a abstraction? as se ae yo ero 18m, ab Explain e features of a class without in IL State whether the given statements are TRUE or FALSE: agent 1L In assembly level language, the instructions are given in rly aware ofits important terms of 0's and 1's. ‘and accelerator. By using 2 PASCAL is a structure oriented programming language. se ec an thus you donot require to Know the internal 43. Machine level language requires a translator to convert input ibe followed when brake is pressed. instructions to be understood by the machine. 44. Compilers and Interpreters are referred to as Language processors. 5. A process according to which a class acquires the characteristies from another class is Called Encapsulation. rack of representing essen packground deta ee arcxample, while driving ct. 0% ror features) vi. clutch, brake, £875 ns g) What does reosabi sed to perform a task in the ae Dong ertance, the component Daring inert ther nk inte ceived clas, This feature 3 aah 6. Procedure oriented program stresses on data. 0 Rann tO pct alos fnton Be 7, Cee is also an object oriented programming language. . 4 ie : ; ‘Ans. An Object Oriented principle that allows a function to be used erie! a oe tonnes pe 8, Function isa st of objets that share the common @) State the Java concept that is implemented through: << é rat acs 10, Encapsulation keeps data safe from outside interference. (i) Toe ot of representing essential features ofa class wit ss ese {a class without inch IL, Name the following: = vee 2 ots : 1. Two categories of Low Level languages sortie : ‘Ams neran an OOP prindple scrrding to which « class 2 es Salle ccna jaiguigee Oe Dine > class. t promotes a characteristic called See, cs S a and function ofa class so that they can ew 3 The structure leoied pean eee @ @ {unit seme as Encapsulation examples of Data ae of Data Abstraction in your daily life questions: ‘of Object Oriented Programming. implements function overloading? Explain. [ICSE 2007) in Java Programming: Output Statement in Java Features of Blue: How to Start Bluel, Execution of Java Program: h INTRODUCTION Java is an object oriented programming language developed primarily by James Gosling and his colleagues at Sun Micro Systems. The language was initially called Oak (named after the Oak trees outside Gosling’s office). In 1991, the Sun Micro Systems (Broomfield, Colorado, USA) developed a complete language named Java, as a part of research work to develop software for consumer electronics. It was developed as a full fledged programming language in which one can accomplish the same sort of tasks and solve similar problems in other programming languages such as BASIC, C++, ete. The platform's independence JAVA is one of the most significant advantages that JAVA has over other languages. It has the capability of moving easily from one computer system to another. JAVA, being an object oriented programming language, has adopted many features of C++. Originally, JAVA was designed to execute applets (the programs executed by using web browser). But gradually, the language gained wide acceptance as a programming language, replacing C or C+. James A. Gosting, (bom on May 19, 1955, near Calgary, Alberta, Canada) is a famous software developer. In 1977, he completed his graduation as a B.Sc. in Computer Science from the University of Calgary In 1981, he was honoured a Ph.D in Computer Science from Camegie Mellon University He developed many | compilers and mail systems. Since 1984, he has been associated with Sun Micro Systems ‘and developed Java programming language in 1991. te vn lp onecad to he Unies Sieg NON Laas eee this achievement. In 2007, he was appointed an Officer which is Canada's highest chvilan honour BASIC FEATURES OF JAVA Java possesses the following features: * Java is an object oriented programming language. + Java programs are both compiled as well as interpreted. ‘© Tt-can access data from a local system as well as from variables and fu The packages ‘javaio’ and ms executed inside ams developed by: ‘java, util” include the classes related to 1/0 and utility functions respectively, The = NGHe " asterisk ) sign denotes that all the jwmlang’is the deta package + Java pe 3 classes of the concerning package will be of Java ‘WOK, ie, vased : made available for use in your program, twill tomatically be imported jean ae case letters are However if specific lass isto be used AY Java program to aval is + Unlike Cv . in the program then the specific class #88@8.and functions. fies for oe name must be used in place of () : For example, import java.util Scanner; creRPRETER 4 in various computer Now, your program can use only the functions of the scanner class of the util java COMPILER AN i orpreter to COnVEr package. Other classes of the package will be ignored. You know npiler and interpreter in di ‘Some of the packages of Java Development Kit are listed below: ; To support classes containing. StingCharacier, Math, : source code into an inter Thread, te at ees > common binary for ‘To support classes to deal with input & output statements spine on which it ong ERIEEMM To support classes to generate applet ~ specific environment gs ieespect and converts i ae vie 20 a ‘To support classes for network related operations and dealing with a URL (Uniform Resource Locator) ‘To support abstract window tool kit and managing GUI (Graphic User Interface) For localising text elements such as dates, times and currency, ete: ‘To support mathematical functions such as square roots (integer & decimal both) programs uses compiler as Well mail RESERVED WoRDS Tt F Teserved words or the keywords are the words which carry special meaning the system compiler. These words are basically used for writing a Java nt. Such words cannot be used for naming a variable in the program. of the reserved words or keywords are listed as below: TUAL MACHINE Ee hine code. It is also kn byte codes received! other non-Java & ses. Each class com function of a lass ion needs to Be package can be included in the program by hen the package containing the func import’. The s JAVA LIBRARIES IN JDK 1.3 # importing a package is as listed below? * import java.io.*; * import java.util; Oancimabane Aci wih ax xd Alone Syste Java Applica! Java Applets (Inte: Basic Structure in Java Prog + Declaration of class It contains ppercase lette * Declaration of main function: The mai inction encloses the P statement pe Themain function is further enclosed within { } under class heading, The termination of each statement must be indicated with a semi-colon, * The closing of curly braces indicates the closing of a block of statement © ndersandig Computer Appian wth Bluel—1x oGRAMMING i the sake of the users to und is followed by a meaningful clas writing a program to find the sum of tWOlml public class Sum. Conventionally, the s, function and class. An example is illustrated below: «, Java programs. They ramcaoadnie [Sige toe comment recess p— Name ofthe cass 4 specter A\Progrim tolfind the sum of two mumbers vablic class Sample a idiuatbie stile Soaee he users, that Tana at { ar . help of Javal public static woid main String erga ive environments lke x to all the resources lone’ (desktop appl int a=10, b=15, e=0; cath; System out printn("The sum of two numbers +e) ee <— Decaration of data (varias) «language that n image is included ina wr to view a page that em and executed, e introduced in | output statement 7) Opening and closing of a lass @): Opening and closing of main function OUTPUT STATEMENT IN JAVA PROGRAMMING ‘The statement which is used to get the output of the program or to display messages on the screen, is given as: ‘System.out.printin0; ‘Syntax: For example, System.out printin(“Welcome to Java Programming”); ‘Output: Welcome to Java Programming, ‘The message needs to be written within double quotes (" ") enclosed within braces. If you want to display a message along with a variable then it could be written as: nt statement is a nom or statement. System.outprintin(’The sum of two numbers is” +p); (Here, p is the variable, which contains the result of the execution.) Output: The sum of two mumbers is 45. <= Note 1. The class name must Java reserved word. 2.As far as possible, the name should be relevant to the program. Blue} is a free Java environment from Monash University, Australia. It is a ‘window based platform for Java Development Kit DK). JDK 15 or 1.6 version dis to be installed before installing Blue}. We can also get more information “about Blue] through the website rwu ej. nconas).eiu. Blue] can be downloaded (the program is ‘The Project with the name ‘Sample’ will appear on Bue] window. Featur ser can perform the . mouse button). ole program font Now, click ‘New Class’ and enter the class name in the text box. Finally, click Ok to create the class icon. ‘Thus, a class with the given name (For example Welcome) will be created, ie., a program file in which your program will be saved, on the hard disk is created ped he desktop to start Ja fen as shown. Dn double clicking the class icon, ‘Welcome’, a sample program is displayed program is only provides assistance to the user. ‘Select the complete program either by dragging the mouse or by using ‘Ctrl +4 key. Delete the sample program by pressing DEL or BACKSPACE key. ect asthe first menu item. Project is Hike contain a number of Blue) classes a5 pig : * name (say, Sample) and finally click on the 4 wn ‘Compile’ button. ing te PO vill appear on the sen + Atr completing . a message will @PPs he is er ee ayntax errors. It MONS, Your prog 10s a comment line. Description ofthe clas (public class Welcome). Here, public keswand ‘48 optional, A class is public by default. ‘Starting of the class block with ‘opening brace [ 4 Fest ecaration ofthe main class, Program execution stars = as function block with opening curly brace 6 = Je the executable output statements which display taal in brackets on the screen. Fed of in function with closing curly brace } ofa Bk with ‘losing curly brace }. EXECUTION OF JAVA PROGRAM When the class is compiled and shows a message ‘no syntax error, it thatthe program is error-free and is ready for execution, Close the window and follow the steps given below: + Select the class icon (Welcome) and click the right button of the mouse, A. drop down menu will appear. + Select and click the option ‘void main (String args [ I) Blue Method cal vod mainstringars) ~ i \Wekamemsin (10 (J coneet + Now, the result will be displayed on the screen. ‘neratoctin to Sve Programing on Muay Pattern See anne i vee Oy Ste oss etcone to St Program Eijoy taneeing 11 suble click the class 4eon. 7 cory changes and teep oe need for execution, REVIEW INSIGHT (@) Give your answer in onetwo word(s}: flese-2007) () Name two types of Java programs @) Name a package that is invoked by default. “Ans. () (a) Stand Alone (b) Java Applets (0 javalang y | Define Byte code. ticse-2010), 5 platform. When compile ‘Ans. The Java compiler converts source code to an intermediate binary code, This Blue] Pe typing errors in code which helps to generate the machine code and is independent of the to some machine, on which the program runs, is known as the ‘Byte code’. (©) What is the use of the keyword ‘import’? UICSE.2011) (d) What does the token ‘keyword’ refer to in the context of Java? {ICSE-2011, 16} ‘The reserved words used in the system that send special meaning to the system compiler and hence cannot be used as a variable name in a program, ae called the keywords. For example, switch, throws, etc. (¢) What isthe role of the keyword ‘void’ in declaring functions? _(ICSE-2011) ns. The keyword void’ signifies that the function doesn't return a valve tothe calling aaa function. a a abet = Stang (© What is meant by @ package? Name any two Java Application Programming. Interface packages. {ICSE-2014, 2016} ns. A package is @ set of various classes. Two examples of Java Application Programming Interface Puckages are- (0 isvaio (0 java.util (State the package that contains the class: Now, you edit the program and make necessary changes §@ ( BufferedReader (Scanner. {ICSE-2015) of the program as shown below: © javaio: (i java.util” 1) Name the person whose contribution is respected for the development of the Java language. {ICSE MODEL} ‘The person respected for the Cerelopese oie arenes etter eee ( Which of the following is valid comment? Square of 22 = 484 (® comment*// comment) of 22 and 15 = 330 (i, ‘Heomment (@) */comment ‘The valid comment is: if) \/comment pf ‘What do understand by the term language processor? {angsege proceor ihe ter ated fortran sch compiler neater, ete. ae

You might also like