Presentation is loading. Please wait.

Presentation is loading. Please wait.

I – UNIT Procedure Oriented Programming

Similar presentations


Presentation on theme: "I – UNIT Procedure Oriented Programming"— Presentation transcript:

1 I – UNIT Procedure Oriented Programming
Object Oriented Programming Paradigm Basic Concepts of OOPS Benefits of OOPS What is Java? Simple Java Program Java Tokens Variables and Constants Data Types Type conversions and Castings Array Operators Control Statements Class fundamentals Declaring Objects 16. Assigning Object References 17. Introducing Methods 18. Constructors 19. this keyword 20. Garbage Collection 21. finalize ( ) Method 22. Overloading Methods 23. Object as parameters 24. Returning Objects 25. Access Control 26. static and final keyword 27. Nested classes and Inner Class 28. Classes with Command Line arguments

2 PROCEDURE ORIENTED PROGRAMMING
1. In Procedural programming, Programmer combines related sequences of statements into one single place, called procedure. 2. A procedure call is used to invoke the procedure. 3. After the sequence is processed, flow of control proceeds right after the position where the call was made. 4. But the approach in oops is that classes and objects are used to model real world entity taking help of methods which performs the functions. 5. This technique is also known as Top – down programming OBJECT ORIENTED PROGRAMMING PARADIGM 1. The major objective of object oriented approach is to eliminate some of the flaws encountered in the procedural approach. 2. OOP treats data as a critical element to the program development and does not allow it to flow freely around the system. 3. It ties data more closely to the function that operate on it an protects it from unintentional modification by other functions.

3 4. OOP allows us to decompose a problem into a number of entities called Objects and then build data and functions (known as methods in Java) around these entities. 5. The combination of data and methods make up an object Methods Data Object = Data + Methods 6. The data of an object can be accessed only by the methods associated with that object. 7. However, methods of one object can access the methods of other object.

4 8. Some of the features of object oriented paradigm are:
Emphasis is on data rather than procedure. Programs are divided into what are known as Objects. Data Structures are designed such that they characterize the objects. Methods that operate on the data of an object are tied together in the data structure. Data is hidden and cannot be accessed by external functions. Objects may communicate with each other through methods. New data and methods can be easily added whenever necessary. Follows bottom – up approach in program design. 9. Our definition of object oriented programming is: Object oriented programming is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and function that can be used as templates for creating copies of such modules on demand.

5 BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING
Class Objects 3. Data Abstraction 4. Data Encapsulation 5. Data Hiding 6. Inheritance 7. Polymorphism 8. Dynamic Binding 9. Message Communication Class The entire set of data and code of an object can be made a user – defined data type using the concept of a class. A class may be thought of as a ‘data type’ and an object as a ‘variable’ of that data type. Once a class has been defined, we can create any number of objects belonging to that class. Each object is associated with the data of type class with which they are created. A class is thus a collection of objects of similar type. 2. Objects Objects are the basic runtime entities in an object – oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program may handle. They may also represent user – defined data types such as vectors and lists. Any programming problem is analyzed in terms of objects and the nature of communication between them.

6 Representation of an object
Person Name BasicPay Salary() Tax() Object Data Methods Representation of an object 3. Data Abstraction, 4. Data Encapsulation and 5. Data Hiding The wrapping up of data and methods into a single unit is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those methods, which are wrapped in the class, can access it, these methods provide the interface between the object’s data and the program,

7 This insulation of the data from direct access by the program is called data hiding. Encapsulation makes it possible for objects to be treated like ‘black boxes’, each performing a specific task without any concern for internal implementation. Data And Method Information “in” Information “out” Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and methods that operator on these attributes, They encapsulate all the essential properties of the objects that are to be created. 6. Inheritance Inheritance is the process by which objects of one class acquire the properties of objects of another class. Inheritance supports the concept of hierarchical classification. In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing one. The new class will have the combined features of both the classes.

8 Thus the real appeal and power of the inheritance mechanism is that it allows the programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor the class in such a way that it does not introduce any undesirable side effects into the rest of the classes. In java, the derived class is known as ‘subclass’ Bird Attributes: Feathers Lay eggs Flying Bird Non FlyingBird

9 7. Polymorphism Polymorphism is another important OOP concept. Polymorphism means the ability to take more than one form. For example, an operation may exhibit different behaviour in different instances. The behaviour depends upon the types of data used in the operation. For example consider the operation of addition. For two number, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation. Consider the following example: Shape Draw() Circle Object Draw(circle) Box Object Draw(box) Triangle Object Draw(triangle) Polymorphism plays an important role in allowing objects having different interval structures to share the same external interface. This means that a general class of operations may be accessed in the same manner even though specific actions associated with each operation may differ. Polymorphism is extensively used in implementing inheritance.

10 Dynamic Binding Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at runtime. It is associated with polymorphism and inheritance. A procedure call associated with a polymorphic reference depends on the dynamic type of that reference. Message Communication An object – oriented program consists of a set of objects that communicate with each other. The process of programming in an object – oriented language, therefore, involves the following basic steps: 1. Creating classes that define objects and their behaviour 2. Creating objects from class definitions. 3. Establishing communication among objects. Objects communicate with one another by sending and receiving information much the same way as people pass messages to one another. The concept of message passing makes it easier to talk about building systems that directly model or simulate their real world counterparts.

11 Network of objects communicating between them

12 Benefits of OOPS 1. Through inheritance, we can eliminate redundant code and extend the use of existing classes. 2. We can build programs from the standard working modules that communicate with one another, rather than having to start writing the code from scratch. This leads to saving of development time and higher productivity. 3. The principle of data binding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program. 4. It is possible to map objects in the problem domain to those objects in the program. 5. It is possible to have multiple objects to coexist without any interference. 6. It is easy to partition the work in a project based on objects. 7. The data – centered design approach enables us to capture more details of a model in an implementable form. 8. Object – Oriented systems can be easily upgraded from small to large systems. 9. Message passing techniques for communication between objects make the interface descriptions with external systems much simpler. 10. Software complexity can be easily managed.

13 Application of OOPS 1. Real – time systems.
2. Simulation and modelling. 3. Object – oriented databases. 4. Hypertext, hypermedia and expertext. 5. AI and expert systems. 6. Neural networks and parallel programming. 7. Decision support. 8. Office automation systems. 9. CIM / CAD / CAM system.

14 The Java Buzzwords or Java Features or Java Characteristics
■ Simple ■ Secure ■ Portable ■ Object-oriented ■ Robust ■ Multithreaded ■ Architecture-neutral ■ Interpreted ■ High performance ■ Distributed ■ Dynamic Simple Java was designed to be easy for the professional programmer to learn and use effectively. Assuming that you have some programming experience, you will not find Java hard to master. If you already understand the basic concepts of object-oriented programming, learning Java will be even easier. Best of all, if you are an experienced C++ programmer, moving to Java will require very little effort. Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most programmers have little trouble learning Java. Also, some of the more confusing concepts from C++ are either left out of Java or implemented in a cleaner, more approachable manner. Beyond its similarities with C/C++, Java has another attribute that makes it easy to learn: it makes an effort not to have surprising features. In Java, there are a small number of clearly defined ways to accomplish a given task. 14

15 Object-Oriented Although influenced by its predecessors, Java was not designed to be source-code compatible with any other language. This allowed the Java team the freedom to design with a blank slate. One outcome of this was a clean, usable, pragmatic approach to objects. Borrowing liberally from many seminal object-software environments of the last few decades, Java manages to strike a balance between the purist’s “everything is an object” paradigm and the pragmatist’s “stay out of my way” model. The object model in Java is simple and easy to extend, while simple types, such as integers, are kept as high-performance nonobjects. Robust The multiplatformed environment of the Web places extraordinary demands on a program, because the program must execute reliably in a variety of systems. Thus, the ability to create robust programs was given a high priority in the design of Java. To gain reliability, Java restricts you in a few key areas, to force you to find your mistakes early in program development. At the same time, Java frees you from having to worry about many of the most common causes of programming errors. Because Java is a strictly typed language, it checks your code at compile time. However, it also checks your code at run time. In fact, many hard-to-track-down bugs that often turn up in hard-to-reproduce run-time situations are simply impossible to create in Java. Knowing that what you have written will behave in a predictable way under diverse conditions is a key feature of Java.

16 To better understand how Java is robust, consider two of the main reasons for program failure: memory management mistakes and mishandled exceptional conditions (that is, run-time errors). Memory management can be a difficult, tedious task in traditional programming environments. For example, in C/C++, the programmer must manually allocate and free all dynamic memory. This sometimes leads to problems, because programmers will either forget to free memory that has been previously allocated or, worse, try to free some memory that another part of their code is still using. Java virtually eliminates these problems by managing memory allocation and deallocation for you. (In fact, deallocation is completely automatic, because Java provides garbage collection for unused objects.) Exceptional conditions in traditional environments often arise in situations such as division by zero or “file not found,” and they must be managed with clumsy and hard-to-read constructs. Java helps in this area by providing object-oriented exception handling. In a well-written Java program, all run-time errors can—and should—be managed by your program. Multithreaded Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish this, Java supports multithreaded programming, which allows you to write programs that do many things simultaneously. The Java run-time system comes with an elegant yet sophisticated solution for multiprocess synchronization that enables you to construct smoothly running interactive systems. Java’s easy-to-use approach to multithreading allows you to think about the specific behavior of your program, not the multitasking subsystem.

17 Architecture-Neutral
A central issue for the Java designers was that of code longevity and portability. One of the main problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorrow—even on the same machine. Operating system upgrades, processor upgrades, and changes in core system resources can all combine to make a program malfunction. The Java designers made several hard decisions in the Java language and the Java Virtual Machine in an attempt to alter this situation. Their goal was “write once; run anywhere, any time, forever.” To a great extent, this goal was accomplished. Interpreted and High Performance Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. This code can be interpreted on any system that provides a Java Virtual Machine. Most previous attempts at crossplatform solutions have done so at the expense of performance. Other interpreted systems, such as BASIC, Tcl, and PERL, suffer from almost insurmountable performance deficits. Java, however, was designed to perform well on very low-power CPUs. As explained earlier, while it is true that Java was engineered for interpretation, the Java bytecode was carefully designed so that it would be easy to translate directly into native machine code for very high performance by using a just-in-time compiler. Java run-time systems that provide this feature lose none of the benefits of the platform-independent code. “High-performance cross-platform” is no longer an oxymoron.

18 Distributed Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols. In fact, accessing a resource using a URL is not much different from accessing a file. The original version of Java (Oak) included features for intraaddress- space messaging. This allowed objects on two different computers to execute procedures remotely. Java revived these interfaces in a package called Remote Method Invocation (RMI). This feature brings an unparalleled level of abstraction to client/ server programming. Dynamic Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the applet environment, in which small fragments of bytecode may be dynamically updated on a running system.

19 What is Java? 1. It is a Pure Object Oriented Programming language. 2. Independent platform language. 3. Java a really simple, reliable, portable, and powerful language. 4. The new language Java on C and C++ but removed a number of features of C and C++. A Simple Java Program class Sample { public static void main(String args[ ]) System.out.println(“Java is Better than C and C++); }

20 JAVA COMPILATION PROCESS
Java Source Code Java Compiler Java Byte Code (Java Class File) Java Interpreter Java Machine Code JAVA VIRTUAL MACHIN (JVM) The Java Compiler is converting from Source code into the Byte code. But java compiler is not executable code. Rather, it is byte code. Bytecode is highly optimized set of instructions designed to be executed by the Java run – time system, which is called the Java Virtual Machine (JVM). That is, in its standard form, the JVM is an interpreter for bytecode.

21 Java Tokens Smallest individual units in a program are known as tokens. The compiler recognizes them for building up expressions and statements. A Java program is a collection of tokens, comments and white spaces. Java language includes five types of tokens. They are: 1. Reserved Keywords 2. Identifiers 3. Literals 4. Operators 5. Separators Reserved Keywords Keywords are an essential part of a language definition. They implement specific features of the language. Java language has reserved 60 words as keywords. Java keywords, combined with operators and separators according to a syntax, form definition of the Java language.

22

23 Identifiers Identifiers are programmer – designed tokens. They are used for nameing classes, methods, variables, objects, labels, packages and interfaces in a program. Java identifiers follow the following rules: 1. They can have alphabets, digits, and the underscore and dollar sign characters. 2. They must not begin with a digit. 3. Uppercase and Lowercase letters are distinct. 4. They can be of any length. Names of all public methods and instance variables start with a leading lowercase letter. Example: average sum When more than one word are used in a name, the second and subsequent words are marked with a leading uppercase letters. dayTemperature firstDayofMonth totalMarks

24 All private and local variables use only lowercase letters combined with underscores
Example: length batch_strength All classes and interfaces start with a leading uppercase letter(and each subsequent word with a leading uppercase letter). Student HelloJava Vehicle MototCycle Variables that represent constant values use all uppercase letters and underscores between words. TOTAL F_MAX PRINCIPAL_AMOUNT

25 Literals Literals in java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables. Java language specifies five major types of literals. They are: Integer literals Floating_point literals Character literals String literals Boolean literals Operators An operator is a symbol that takes one or more arguments and operates on them to produce a result. Arithmetic operators Relational operators Logical operators Assignment operators Increment and Decrement operators Conditional operators Bitwise operators Special operators

26 Separators Separators are symbols used to indicate where groups of code are divide and arranged. They basically define the shape and function of our code. Name What it is used for paraentheses() Method definitions and invocation braces { } Automatically initialized arrays brackets [ ] declare array types semicolon ; Used to separate statements comma , Used to separate variable declaration period Used to separate package name

27 Literals Literals in java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables. Java language specifies five major types of literals. They are: Integer literals Floating_point literals Character literals String literals Boolean literals

28 Single Character Literals
Java Literals Character Literals Boolean Literals Numeric Literals Integer Literals Real Single Character Literals String Integer Literals An Integer literal refers to a sequence of digits. There are two types of integers. Namely, Decimal integer Literals Ex: Valid Ex: ,000 $ Invalid Hexadecimal integer Literals Ex: 0X2 0X9F 0Xbcd 0x 28

29 are all valid real literals.
Integer literals are inadequate to represent quantities that vary continuously, such as distances, height temperatures, prices and so on. These quantities are represented by numbers containing fractional par, like Such numbers are called real (or floating point) numbers. Further examples of real literals are: These numbers are shown in decimal notation, having a whole number followed by a decimal part and the fractional part, which is an integer. It is possible that the number may not have. digits before d decimal point, or digits after the decimal point. That is, are all valid real literals. A real literal may also be expressed in exponential (or scientific) notation. For example, the value may be written as e2 in exponential notation. e2 means multiply by 102. The general form is: mantissa e exponent The mantissa is either a real number expressed in decimal notation or an integer. The exponent integer with an optional plus or minus sign. The letter' e' separating the mantissa and the exponent o' be written in either lowercase or uppercase. Since the exponent causes the decimal point to 'float', t!. notation is said to represent a real number in floating-point form. Examples of legal floating-points literals are: 29

30 Embedded white (blank) space is not allowed in any numeric constant.
Example: 0.65e4 12e e+5 3.18E E-1 Embedded white (blank) space is not allowed in any numeric constant. Exponential notation is useful for representing numbers that are either very large or very small magnitude. For example, may be written as 7.5E9 or 75E8. Similarly, , equivalent to -3.68E-7. A floating-point literal may thus comprise four parts: . a whole number . a decimal point . a fractional part . an exponent 30

31 There are two Boolean literal values: . true . false
Boolean Literals There are two Boolean literal values: . true . false Single Character Literals A single-character literal (or simply character constant) contains a single character enclosed within a pair of single quote marks. Examples of character in the examples above constants are: ‘5’ ‘X’ ‘;’ ‘ ‘ String Literals A string literal is a sequence of characters enclosed between double quotes. The characters may be alphabets, digits, special characters and blank spaces. Examples are: “Hello C#” “2001” “WELL DONE” “?.....!” “5+3” “X” 31

32 Backslash Character Literal
Java supports some special backslash character constants that are used in output methods. For example, ue the symbol '\n' stands for a new-line character. A list of such backs lash character literals is given in CONSTANT MEANING ‘\a’ Alert ‘\b’ Back space ‘\f’ Form feed ‘\n New – line ‘\r’ Carriage return ‘\t’ Horizontal tab ‘\v’ Vertical tab ‘\’’ Single quote ‘\\’ Backslash ‘\o’ Null ‘\’’’ Double quote 32

33 1. They must not begin with a digit.
VARIABLE A variable is an identifier that denotes a storage location used to store a data value. Unlike constant that remain unchanged during the execution of a program, a variable may take different values at different times during the execution of the program. Every variable has a type that determines what values ca be stored in the variable. A variable name can be chosen by the programmer in a meaningful way so as to reflect what represents in the program. Some examples of variable names are: average height totaCheight classStrength As mentioned earlier, variable names may consist of alphabets, digits and the underscore ( - ), subject to the following conditions: 1. They must not begin with a digit. 2. Uppercase and lowercase are distinct. This means that the variable Total is not the same as total or TOTAL. 3. It should not be a keyword. 4. White space is not allowed. 5. Variable names can be of any length. 33

34 CONSTANTS Constants in Java refer to fixed values that do not change during the execution of a program. Java supports several types of constants:

35 Single Character Constants
Java Constants Character Constants Boolean Constants Numeric Constants Integer Constants Real Single Character Constants String Integer Constants An Integer literal refers to a sequence of digits. There are two types of integers. Namely, Decimal integer Constants Ex: Valid Ex: ,000 $ Invalid Hexadecimal integer Constants Ex: 0X2 0X9F 0Xbcd 0x 35

36 are all valid real constants.
Integer Constants are inadequate to represent quantities that vary continuously, such as distances, height temperatures, prices and so on. These quantities are represented by numbers containing fractional par, like Such numbers are called real (or floating point) numbers. Further examples of real Constants are: These numbers are shown in decimal notation, having a whole number followed by a decimal part and the fractional part, which is an integer. It is possible that the number may not have. digits before d decimal point, or digits after the decimal point. That is, are all valid real constants. A real literal may also be expressed in exponential (or scientific) notation. For example, the value may be written as e2 in exponential notation. e2 means multiply by 102. The general form is: mantissa e exponent The mantissa is either a real number expressed in decimal notation or an integer. The exponent integer with an optional plus or minus sign. The letter' e' separating the mantissa and the exponent o' be written in either lowercase or uppercase. Since the exponent causes the decimal point to 'float', t!. notation is said to represent a real number in floating-point form. Examples of legal floating-points constants are: 36

37 Embedded white (blank) space is not allowed in any numeric constant.
Example: 0.65e4 12e e+5 3.18E E-1 Embedded white (blank) space is not allowed in any numeric constant. Exponential notation is useful for representing numbers that are either very large or very small magnitude. For example, may be written as 7.5E9 or 75E8. Similarly, , equivalent to -3.68E-7. A floating-point literal may thus comprise four parts: . a whole number . a decimal point . a fractional part . an exponent 37

38 There are two Boolean constant values: . true . false
Single Character Constant A single-character constant (or simply character constant) contains a single character enclosed within a pair of single quote marks. Examples of character in the examples above constants are: ‘5’ ‘X’ ‘;’ ‘ ‘ String Constant A string constant is a sequence of characters enclosed between double quotes. The characters may be alphabets, digits, special characters and blank spaces. Examples are: “Hello C#” “2001” “WELL DONE” “?.....!” “5+3” “X” 38

39 Backslash Character Constant
Java supports some special backslash character constants that are used in output methods. For example, ue the symbol '\n' stands for a new-line character. A list of such backs lash character literals is given in CONSTANT MEANING ‘\a’ Alert ‘\b’ Back space ‘\f’ Form feed ‘\n New – line ‘\r’ Carriage return ‘\t’ Horizontal tab ‘\v’ Vertical tab ‘\’’ Single quote ‘\\’ Backslash ‘\o’ Null ‘\’’’ Double quote 39

40 DATA TYPES Every variable in java has a data type. Data types specify the size and type of values that can be stored. Java language is rich in its data types. The variety of data types available allow the programmer to select the type appropriate to the needs of the applications. DATA TYPES IN JAVA Premitive (Intrinsic) Non – Primitive ( Derived Classes Arrays Numeric Non -Numeric Interface Integer Floating - Point Character Boolean

41 Integer Types Type Size Minimum Size Maximum Size byte One byte -128
short int long Type Size Minimum Size Maximum Size byte One byte -128 127 short Two byte -32,768 32, 767 int Four byte -2, 147, 483, 648 2, 147, 483, 647 long Eight byte -9, 223, 372, 036, 854, 775, 808

42 Floating Point Types Type Size Minimum Size Maximum Size Float 4 bytes
Double Type Size Minimum Size Maximum Size Float 4 bytes 3.4e – 038 3.4e + 038 Double 8 bytes 1.7e – 308 1.7e + 308

43 Character Type In order to store character constants in memory. Java provides a character data type called char. The char type assumes a size of 2 bytes but, basically, it can hold only a single character Boolean Type Boolean type is used when we want to test a particular condition during the execution of the program. There are only two values that a boolean type can take: true or false. Remember, both these words have been declared as keywords. Boolean type is denoted by the keyword boolean and uses only one bit of storage.

44 Arithmetic Operations
TYPE CONVERSION Type Conversion Casting Operations Arithmetic Operations Explicit Conversion Implicit Conversion Convert a data of one type to another before it is used in arithmetic operations or to store a value of one type into a variable of another type. Example: byte b1 = 50; byte b2 = 60; byte b3 = b1 + b2; Error: “cannot implicitly covert type int to type byte” int b3 = b1 + b2; // No Error In C#, type conversions take place in two ways 1. Implicit conversions 2. Explicit conversions 44

45 Some Examples of implicit conversion are: byte x1 = 75; short x2 = x1;
Implicit Conversions The conversion can always be performed without any loss of data. For numeric types, this implies that the destination type can fully represent the range of the source type. For example, a short can be converted implicitly to an int, because the short range is a subset of the int range. Therefore, short b = 75; int a = b; C# does the conversion automatically. An implicit conversion is also known as automatic type conversion. The process of assigning a smaller type to a larger one is known as widening or promotion. Some Examples of implicit conversion are: byte x1 = 75; short x2 = x1; int x3 = x2; long x4 = x3; float x5 = x4; decimal x6 = x4; 45

46 Java Conversion hierarchy chart
8 – bit types byte 16 – bit types short char 32 – bit types int long 64 – bit types float double 46

47 type variable1 = (type) variable2
Explicit Conversions The process of assigning a larger type to a smaller one is known as norrowing. The norrowing may result in loss of information. There are many conversions that cannot be implicitly made between types. If we attempt such conversions, the compiler will give an error message. For example, the following conversions cannot be made implicitly: int to short int to long long to int float to int decimal to any numeric type any numeric type to char However, we can explicitly carry out such conversions using the ‘cast’ operator. The process is known as casting and is done as follows: type variable1 = (type) variable2 47

48 Automatic Type Promotion in Expressions
Example: int m = 50; byte n = (byte) m; long x = 1234L; int y = (int) x; float f = 50.0F long y = (long) f; Automatic Type Promotion in Expressions In addition to assignments, there is another place where certain type conversions may occur: in expressions. To see why, consider the following. In an expression, the precision required of an intermediate value will sometimes exceed the range of either operand. For example, examine the following expression: byte a = 40; byte b = 50; byte c = 100; int d = a * b / c; The result of the intermediate term a * b easily exceeds the range of either of its byte operands. To handle this kind of problem, Java automatically promotes each byte or short operand to int when evaluating an expression. This means that the subexpression a * b is performed using integers—not bytes. Thus, 2,000, the result of the intermediate expression, 50 * 40, is legal even though a and b are both specified as type byte. As useful as the automatic promotions are, they can cause confusing compile-time errors. For example, this seemingly correct code causes a problem: b = b * 2; // Error! Cannot assign an int to a byte! 48

49 The Type Promotion Rules
The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte variable. However, because the operands were automatically promoted to int when the expression was evaluated, the result has also been promoted to int. Thus, the result of the expression is now of type int, which cannot be assigned to a byte without the use of a cast. This is true even if, as in this particular case, the value being assigned would still fit in the target type. In cases where you understand the consequences of overflow, you should use an explicit cast, such as byte b = 50; b = (byte)(b * 2); which yields the correct value of 100. The Type Promotion Rules In addition to the elevation of bytes and shorts to int, Java defines several type promotion rules that apply to expressions. They are as follows. First, all byte and short values are promoted to int, as just described. Then, if one operand is a long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands is double, the result is double. The following program demonstrates how each value in the expression gets promoted to match the second argument to each binary operator:

50 class Promote { public static void main(String args[]) byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = .1234; double result = (f * b) + (i / c) - (d * s); System.out.println((f * b) + " + " + (i / c) + " - " + (d * s)); System.out.println("result = " + result); }

51 OPERATORS 51

52 Subtraction or Unary Minus
C# supports a rich set of operators. Arithmetic operators Relational operators Logical operators Assignment operators Increment and Decrement operators Conditional operators Bitwise logical operators Special operators ARITHMETIC OPERATORS Integer Arithmetic a % b equivalent to a – ( a / b ) * b -14 % 3 = -2 -14 % -3 = -2 -14 % -3 = 2 Real Arithmetic Mixed – Mode Arithmetic Ex: / 10.0 produces the result 1.5 15 / 10 produces the result 1 Operator Meaning + Addition or Unary plus - Subtraction or Unary Minus * Multiplication / Division % Modulo Division 52

53 Is greater than or equal to
RELATIONAL OPERATOR LOGICAL OPERATOR Operator Meaning < Is less than <= Is less than or equal to > Is greater than >= Is greater than or equal to == Is equal to != Is not equal to Operator Meaning && Logical AND || Logical OR ! Logical NOT BITWISE LOGICAL OPERATOR C# supports operators that may be used for manipulation of data at bit level. These operators may be used for testing the bits or shifting them to the right or left. Bitwise operators may not be applied to floating – point data. Operator Meaning & Bitwise Logical AND | Bitwise Logical OR ^ Bitwise Logical XOR ~ One’s Complement << Left Shift >> Right Shift 53

54 Bitwise Complement ( ~ )
Variable Value Binary Pattern X 23 ~X 132 Y FF ~Y 00 Shift Operations Left Shift Variable Value Binary Pattern X (8 bits) X << 3 the bit pattern of X value is left shifted by thrice. The Resultant bit pattern will be 54

55 Variable Value Binary Pattern Y 41 0 0 1 0 1 0 0 1
Right Shift Variable Value Binary Pattern Y Y>>3 the bit pattern of the Y value is right shifted by thrice. The Resultant bit pattern will be Bitwise Logical AND Bitwise Logical OR Bitwise Exclusive OR Variable Value Binary Pattern X 5 Y 2 X & Y A 6 B 3 A & B Variable Value Binary Pattern X 5 Y 2 X | Y 7 A 6 B 1 A & B Variable Value Binary Pattern X 5 Y 2 X ^ Y 7 A 6 B 3 A ^ B 55

56 op - is the binary operator v op= exp is equivalent to v = v op(exp);
Assignment Operator Assignment operators are used to assign the value of an expression to a variable. C# has a set of ‘shorthand’ assignment operators which are used in the form v op= exp v - is the variable exp - is the expression op - is the binary operator v op= exp is equivalent to v = v op(exp); Ex: x + = y + 1; is equivalent to x = x + (y +1) Advantages: . What appears on the left – hand side need not be repeated and therefore it becomes easier to write. . The statement is more concise and easier to read. . The use of shorthand operators results in a more efficient code. 56

57 Increment and Decrement Operator The operators are ++ and - -
++ means Increment Operator - - means Decrement Operator The operator ++ adds 1 to the operand while – subtracts 1. Both are unary operators and are used in the following form: ++m; or m++ --m or m— ++m; is equivalent to m = m + 1 (or m + = 1;) --m; is equivalent t o m = m – 1 (or m - = 1;) We use the increment and decrement operators extensively in for and while loops For Example: Case 1 m = 5; y = ++m; The statement a [ i ++ ] = 10; is equivalent to a [ i ] = 10; i = i + 1; Case 2 m = 5; y = m--; 57

58 Special Operators Conditional Operator
It is also known as Ternary operator Syntax: exp_1? exp_2: exp_3 Special Operators Instanceof Operator The instanceof is an object reference operator and returns true if the object on the left – hand side is an instance of the class given on the right – hand side. This operator allows us to determine whether the object belongs to a particular class or not. Example: person instanceof student Dot Operator The dot operator (.) is used to access the instance variables and methods of class objects. person1.age //Reference to the variable age person1.salary( ) //Reference to the method salary( ) 58

59 DECISION MAKING – BRANCHING and LOOPING
59

60 Decision making with IF statement 1. Simple if statement
2. if… else statement 3. Nested if…else statement 4. else if ladder Simple if statement if (Boolean-expression) { Statement-block } Statement – x if…else statement if (Boolean-expression) { True-block statement(s) } else Flase-block statement(s) Statement-x; 60

61 Nesting if…else statement if (Boolean-expression) {
True-block statement(S) True-block Statement(s) } else False-block Statement(s) False-block statement(s) 61

62 Default-Statement-x;
else if Ladder if (condition_1) Statement_1; else if (condition_2) Statement_2; else if (condition_3) Statement_3; . else if (condition_n) Statement_n; else Default-Statement-x; 62

63 THE SWITCH STATEMENT switch (expression) { case value_1: block_1;
break; case value_2: block_2; case value_3: block_3; default: default_block } Statement_x; 63

64 DECISION MAKING AND LOOPING
The C# language provides for four constructs for performing loop operations. They are: The while statement The do statement The for statement The do statement Syntax: initialization do { Body of the Loop } while (test_condition); The while statement Syntax: initialization; while(test_condition) { Body of the Loop } The for statement Syntax: for (initialization;test_condition;increment) { Body of the Loop } 64

65 Case 6: for (j = 1000; j>0; j = j – 1); Case 7:
Additional Features of the for Loop Case 1: p = 1; for (n = 0; n<17;++n) can be rewritten as for (p=1,n=0;n<17;++n) Case 2: for (n=1,m=50;n<=m; n=n+1,m=m-1) { } Case 3: sum = 0; for ( i =1, i<20 && sum <100; i++) Case 4: for (x = (m+n)/2; x>0;x = x/2) Case 5: m = 5; for (;m != 100;) System.out.println(m); m = m + 5; Case 6: for (j = 1000; j>0; j = j – 1); Case 7: for (j = 1000;j>0; j= j-1); 65

66 Jumps in Loops break; continue; goto; class Gobreakcontinue {
public static void main(String args[ ] ) for (int i = 1;i< 100;i++) System.out.println( “ “); if (i >= 10) Break; for(int j = 1;j<100;j++) System.out.println(“ * “); if (j == i) goto loop1; } loop: continue; System.out.println(“Termination by BREAK”); 66

67 ARRAY 67

68 3. Multi Dimensional Array
Array is collection of homogenous Data items. Array is classified into three types. 1. One Dimensional Array 2. Two Dimensional Array 3. Multi Dimensional Array One Dimensional Array Two Dimensional Arrays X Y 68

69 Multidimensional Arrays
X Z Creating an Array 1. Declaring the array 2. Creating memory locations 3. Putting values into the memory locations. 1. Declaration of Arrays Syntax: type [ ] arrayname; Example: int [ ] counter; float [ ] marks; int [ ] x,y; 69

70 2. Creating memory locations Syntax: arrayname = new type [size];
Examples: number = new int [5]; average = new float [10]; 3. Declaration and Creation in one step Syntax: type [ ] arrayname = new type [size]; Examples: int [ ] number = new int [5]; 4. Initialization of Arrays Syntax: type [ ] arrayname = {list of values}; Example: int [ ] number = {32,45,34,56,34}; int [ ] number = new int [3] {10,20,30}; 70

71 class NumberSorting { public static void main(String args[]) int number[] = {55,40,80,65,71}; int n = number.length; System.out.println("Given List"); for(int i = 0;i<n;i++) System.out.println(" " + number[i]); } System.out.print("\n"); for(int i = 0;i < n; i++) for(j = 1;j < n; j++) if (number[i] < number [j]) int temp = number[i]; number[i] = numbdf[j]; number[j] = temp;

72 System.out.println("Sorted list:");
for(int i = 0;i < n;i++) { System.out.println(" " + number[i]); } System.out.println(" ");

73 Two Dimensional Array Case:
It is possible to assign an array object to another. Ex: int [ ] a = {1,2,3}; int [ ] b; b = a; Two Dimensional Array Declaration for the Two Dimensional Array int [ ][ ] myArray; myArray = new int[3,4]; OR int [ ][ ] myArray = new int[3,4]; int[ ][ ] table = {{0,0,0},{1,1,1}}; 73

74 class MultiTable { final static int ROWS = 20; final static int COLUMNS = 20; public static void main(String args[]) int product[][] = new int[ROWS][COLUMNS]; int row,column; System.out.println("Multiplication Table"); System.out.println(" "); int i,j; for(i=10;i<ROWS;i++) for(j=10;j<COLUMNS;j++) product[i][j] = i * j; System.out.println(" " + product[i][j]); }

75 int [ ] [ ] x = new int [3] [ ]; //Three rows array
Variable – Size Arrays Variable – Size array is called Array of Array or Nested Array or Jagged Array Ex: int [ ] [ ] x = new int [3] [ ]; //Three rows array x [0] = new int [2] //First Rows has two elements x [1] = new int [4] //Second Rows has four elements x [2] = new int [3] //Third Rows has three elements x[0] x[1] x[2] x[0] [1] x[1] [3] x[2] [2] 75

76 public static void main(String args[ ])
public class MyArrayc2 { public static void main(String args[ ]) BufferedReader br = new BufferedRead(new InputStreamReader(System.in)) int [ ][ ]arr=new int[4][ ]; arr[0]=new int[3]; arr[1]=new int[2]; arr[2]=new int[5]; arr[3]=new int[4]; System.out.println("Enter the numbers for Jagged Array"); for(int i=0 ; i < arr.Length ; i++) for(int x=0 ; x < arr[i].Length ; x++) String st= br.readLine(); int num=Integer.parseInt(st); arr[i][x]=num; } 76

77 System.out.println("Printing the Elemnts");
for(i=0 ; i < arr.Length ; i++) { for(y=0 ; y < arr[i].Length ; y++) System.out.println(arr[x][y]); System.out.println("\0"); } 77

78 CLASS FUNDAMENTALS

79 The General Form of a Class
When you define a class, you declare its exact form and nature. You do this by specifying the data that it contains and the code that operates on that data. While very simple classes may contain only code or only data, most real-world classes contain both. As you will see, a class’ code defines the interface to its data. A class is declared by use of the class keyword. The classes that have been used up to this point are actually very limited examples of its complete form. Classes can (and usually do) get much more complex. The general form of a class definition is shown here: class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) // body of method } type methodname2(parameter-list) type methodnameN(parameter-list)

80 // APPLICATION OF CLASSES AND OBJECTS
using System; class Rectangle { public int length, width; public void GetData(int x,int y) length = x; width = y; } public int RectArea () int area = length * width; return (area); class RectArea public static void Main() int area1,area2; Rectangle rect1 = new Rectangle (); Rectangle rect2 = new Rectangle (); rect1.length = 15; rect1.width = 10; area1 = rect1.length * rect1.width ; rect2.GetData (20,10); area2 = rect2.RectArea (); System.out.println("Area1 = " + area1); System.out.println("Area2 = " + area2);

81 Assigning Object Reference Variables
Object reference variables act differently than you might expect when an assignment takes place. For example, what do you think the following fragment does? Box b1 = new Box(); Box b2 = b1; You might think that b2 is being assigned a reference to a copy of the object referred to by b1. That is, you might think that b1 and b2 refer to separate and distinct objects. However, this would be wrong. Instead, after this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are the same object. This situation is depicted here: Although b1 and b2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to b1 will simply unhook b1 from the original object without affecting the object or affecting b2. For example: Box b1 = new Box(); Box b2 = b1; // ... b1 = null; Here, b1 has been set to null, but b2 still points to the original object.

82 ADDING METHODS class Box { double width; double height; double depth;
// display volume of a box void volume() System.out.print("Volume is "); System.out.println(width * height * depth); } class BoxDemo3 public static void main(String args[] Box mybox1 = new Box(); Box mybox2 = new Box();

83 // assign values to mybox1's instance variables
mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // display volume of first box mybox1.volume(); // display volume of second box mybox2.volume(); }

84 Returning a Value class Box { double width; double height;
double depth; // compute and return volume double volume() return width * height * depth; } class BoxDemo4 public static void main(String args[]) Box mybox1 = new Box(); Box mybox2 = new Box(); double vol;

85 // assign values to mybox1's instance variables
mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); }

86 Adding a Method That Takes Parameters
class Box { double width; double height; double depth; // compute and return volume double volume() return width * height * depth; } // sets dimensions of box void setDim(double w, double h, double d) width = w; height = h; depth = d;

87 class BoxDemo5 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // initialize each box mybox1.setDim(10, 20, 15); mybox2.setDim(3, 6, 9); // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); }

88 Constructors class Box { double width; double height; double depth;
// This is the constructor for Box. Box() System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // compute and return volume double volume() return width * height * depth;

89 class BoxDemo6 { public static void main(String args[]) // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); }

90 Parameterized Constructors
class Box { double width; double height; double depth; // This is the constructor for Box. Box(double w, double h, double d) width = w; height = h; depth = d; } // compute and return volume double volume() return width * height * depth;

91 class BoxDemo7 { public static void main(String args[]) // declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(3, 6, 9); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); }

92 The this Keyword Garbage Collection
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. You can use this anywhere a reference to an object of the current class’ type is permitted. To better understand what this refers to, consider the following version of Box( ): // A redundant use of this. Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } Garbage Collection Since objects are dynamically allocated by using the new operator, you might be wondering how such objects are destroyed and their memory released for later reallocation. In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete operator. Java takes a different approach; it handles deallocation for you automatically. The technique that accomplishes this is called garbage collection.

93 The finalize( ) Method The constructor method is used to initialize an object when it is declared. This process is known as initalisation. Similarly, Java supports a concept called finalization, which is just opposite to initialization. We know that java run – time is an automatic garbage collecting system. It automatically frees up the memory resources used by the objects. But objects may hold other non – object resources such as file descriptors or window system fonts. The garbage collector cannot free these resources. In order to free resources we must use a finaliser method. This is similar to destructor in C++. The finalize( ) method has this general form: protected void finalize( ) { // finalization code here }

94 Overloading Methods class OverloadDemo { void test()
System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) System.out.println("a: " + a); // Overload test for two integer parameters. void test(int a, int b) System.out.println("a and b: " + a + " " + b); // overload test for a double parameter double test(double a) System.out.println("double a: " + a); return a*a;

95 class Overload { public static void main(String args[]) OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); }

96 Overloading Constructors
class Box { double width; double height; double depth; // constructor used when all dimensions specified Box(double w, double h, double d) width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box

97 // constructor used when cube is created
Box(double len) { width = height = depth = len; } // compute and return volume double volume() return width * height * depth; class OverloadCons public static void main(String args[]) // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol;

98 // get volume of first box
vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); }

99 Using Objects as Parameters
// Objects may be passed to methods. class Test { int a, b; Test(int i, int j) a = i; b = j; } // return true if o is equal to the invoking object boolean equals(Test o) if(o.a == a && o.b == b) return true; else return false; class PassOb public static void main(String args[]) Test ob1 = new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -1); System.out.println("ob1 == ob2: " + ob1.equals(ob2)); System.out.println("ob1 == ob3: " + ob1.equals(ob3));

100 Returning Objects // Returning an object. class Test { int a;
Test(int i) a = i; } Test incrByTen() Test temp = new Test(a+10); return temp; class RetOb public static void main(String args[]) Test ob1 = new Test(2); Test ob2; ob2 = ob1.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase: “ + ob2.a);

101 Access Specifier Accessing Level
ACCESS CONTROL Access Specifier Accessing Level private Same Class in Same Package private protected Sub Class in Same Package friendly (not a keyword Non – Sub Class in Same Package protected Sub Class in Other Package public Other Class in Other Package class Test { int a; // default access public int b; // public access private int c; // private access // methods to access c void setc(int i) // set c's value c = i; } int getc() // get c's value return c; } }

102 class AccessTest { public static void main(String args[]) Test ob = new Test(); // These are OK, a and b may be accessed directly ob.a = 10; ob.b = 20; // This is not OK and will cause an error // ob.c = 100; // Error! // You must access c through its methods ob.setc(100); // OK System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc()); }

103 Understanding static There will be times when you will want to define a class member that will be used independently of any object of that class. Normally a class member must be accessed only in conjunction with an object of its class. However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist. Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable. Methods declared as static have several restrictions: ■ They can only call other static methods. ■ They must only access static data. ■ They cannot refer to this or super in any way.

104 class UseStatic { static int a = 3; static int b; static void meth(int x) System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static System.out.println("Static block initialized."); b = a * 4; public static void main(String args[ ]) meth(42);

105 Nested and Inner Classes
It is possible to define a class within another class; such classes are known as nested classes. The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is defined within class A, then B is known to A, but not outside of A. A nested class has access to the members, including private members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class. There are two types of nested classes: static and non-static. A static nested class is one which has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used. The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. Thus, an inner class is fully within the scope of its enclosing class.

106 // Demonstrate an inner class.
class Outer { int outer_x = 100; void test() Inner inner = new Inner(); inner.display(); } // this is an inner class class Inner void display() System.out.println("display: outer_x = " + outer_x); class InnerClassDemo public static void main(String args[]) Outer outer = new Outer(); outer.test(); } }

107 Using Command-Line Arguments
Sometimes you will want to pass information into a program when you run it. This is accomplished by passing command-line arguments to main( ). A command-line argument is the information that directly follows the program’s name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy—they are stored as strings in the String array passed to main( ). For example, the following program displays all of the command-line arguments that it is called with: // Display all command-line arguments. class CommandLine { public static void main(String args[]) for(int i=0; i<args.length; i++) System.out.println("args[" + i + "]: " + args[i]); } Try executing this program, as shown here: java CommandLine this is a test When you do, you will see the following output: args[0]: this args[1]: is args[2]: a args[3]: test args[4]: 100 args[5]: -1

108 II – UNIT Inheritance Inheritance with Super Keyword
Inheritance with Method Overriding Inheritance with Abstract Class Inheritance with Final Keyword Interfaces Packages String Functions StringBuffer Functions

109 INHERITANCE

110 INHERITANCE A B What is Inheritance?
Inheritance is the mechanism which allows a class B to inherit properties/characteristics- attributes and methods of a class A. We say “B inherits from A". A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class What are the Advantages of Inheritance 1. Reusability of the code. 2. To Increase the reliability of the code. 3. To add some enhancements to the base class.

111 Inheritance achieved in two different forms
1. Classical form of Inheritance 2. Containment form of Inheritance Classical form of Inheritance We can now create objects of classes A and B independently. Example: A a; //a is object of A B b; //b is object of B A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class

112 In Such cases, we say that the object b is a type of a
In Such cases, we say that the object b is a type of a. Such relationship between a and b is referred to as ‘is – a’ relationship Example 1. Dog is – a type of animal 2. Manager is – a type of employee 3. Ford is – a type of car Animal Horse Dog Lion

113 Containment Inheritance
We can also define another form of inheritance relationship known as containership between class A and B. Example: class A { } class B A a; // a is contained in b B b;

114 In such cases, we say that the object a is contained in the object b
In such cases, we say that the object a is contained in the object b. This relationship between a and b is referred to as ‘has – a’ relationship. The outer class B which contains the inner class A is termed the ‘parent’ class and the contained class A is termed a ‘child’ class. Example: 1. car has – a radio. 2. House has – a store room. 3. City has – a road. Car object Radio object

115 1. Single Inheritance (Only one Super Class and One Only Sub Class)
Types of Inheritance 1. Single Inheritance (Only one Super Class and One Only Sub Class) 2. Multilevel Inheritance (Derived from a Derived Class) 3. Hierarchical Inheritance (One Super Class, Many Subclasses) 1. Single Inheritance (Only one Super Class and Only one Sub Class) A B

116 2. Multilevel Inheritance (Derived from a Derived Class)
B C 4. Hierarchical Inheritance (One Super class, Many Subclasses) A B C D

117 Single Inheritance (Only one Super Class and One Only Sub Class)
class Room { protected int length, breadth; Room() length = 10; breadth = 20; } void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom() length = 10; breadth = 20; height = 30; void HallRoom_Volume() System.out.println("The Valoume of the HallRoom is:" + (length * breadth * height));

118 class MainRoom { public static void main(String [] args) HallRoom hr = new HallRoom(); hr.Room_Area(); hr.HallRoom_Volume(); }

119 Multilevel Inheritance (Derived from a Derived Class)
class Room { protected int length, breadth; Room() length = 10; breadth = 20; } void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom() length = 10; breadth = 20; height = 30; void HallRoom_Volume() System.out.println("The Volume of the HallRoom is:" + (length * breadth * height));

120 class BedRoom extends HallRoom
{ int height_1; BedRoom() length = 10; breadth = 20; height = 30; height_1 = 40; } void BedRoom_Volume1() System.out.println("The Volume of the the BedRoom is:" + (length * breadth * height * height_1)); class MainRoom public static void main(String [] args) BedRoom br = new BedRoom(); br.Room_Area(); br.HallRoom_Volume(); br.BedRoom_Volume1();

121 Hierarchical Inheritance (One Super Class, Many Subclasses)
class Room { protected int length, breadth, height; Room() length = 10; breadth = 20; height = 30; } class HallRoom extends Room void HallRoom_Area() System.out.println("The Area of the HallRoom is:" + (length * breadth));

122 class BedRoom extends Room
{ void BedRoom_Volume() System.out.println("The Volume of the BedRoom is:" + (length * breadth * height)); } class MainRoom public static void main(String [] args) HallRoom hr =new HallRoom(); BedRoom br = new BedRoom(); hr.HallRoom_Area(); br.BedRoom_Volume();

123 INHERITANCE WITH super KEYWORD

124 The purpose of the ‘super’ keyword:
1. Using super to call Superclass Constructors 2. Using super to call Superclass Methods Using super to Call Superclass Constructor A Subclass can call a constructor method defined by its superclass by use of the following form of super: super (parameter – list) Here, parameter – list specifies any parameter needed by the constructor in the superclass, super() must always be the first statement executed inside a subclass constructor. Restriction of the Subclass constructor 1. super may only be used within a subclass constructor method. 2. The call to superclass constructor must appear as the first statement within the subclass constructor 3. The parameters in the super call must match the order and type of the instance variable declared in the superclass.

125 class Room { protected int length, breadth, height; Room(int length, int breath) this.length = length; this.breadth = breath; } void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom(int length, int breath, int height) super(length,breath); this.height = height; void HallRoom_Volume() System.out.println("The Volume of the HallRoom is:" + (length * breadth * height));

126 class MainRoom { public static void main(String [] args) HallRoom hr =new HallRoom(10,20,30); hr.Room_Area(); hr.HallRoom_Volume(); }

127 //super keyword in Multilevel Inheritance
class Room { protected int length, breadth, height; Room(int length, int breath) this.length = length; this.breadth = breath; } void Room_Area() System.out.println("The Area of the Room is:" + (length * breadth)); class HallRoom extends Room int height; HallRoom(int length, int breath, int height) super(length,breath); this.height = height; void HallRoom_Volume() System.out.println("The Volume of the HallRoom is:" + (length * breadth * height));

128 class BedRoom extends HallRoom
{ int height_1; BedRoom(int length, int breath, int height, int height_1) super(length,breath,height); this.height_1 = height_1; } void BedRoom_Volume_1() System.out.println("The Volume 1 of the BedRoom is:" + (length * breadth * height * height_1)); class MainRoom public static void main(String [] args) BedRoom br =new BedRoom(10,20,30,40); br.Room_Area(); br.HallRoom_Volume(); br.BedRoom_Volume_1();

129 2. Using super to Call Superclass Method
//super keyword call Super Class Methods class Room { void Room_Super() System.out.println("The Room Base is Displayed"); } class HallRoom extends Room void HallRoom_Intermetiate() System.out.println("The Hall Room is Displayed"); class BedRoom extends HallRoom void BedRoom_Sub() super.Room_Super(); super.HallRoom_Intermetiate(); System.out.println("The Bed Room is Displayed"); class MainRoom public static void main(String [] args) BedRoom br = new BedRoom(); br.BedRoom_Sub(); } }

130 Inheritance with Method Overriding

131 1. Method overriding in java means a subclass method overriding a super
2. Superclass method should be non-static. 3. Subclass uses extends keyword to extend the super class. 4. In the example class B is the sub class and class A is the super class. 5. In overriding methods of both subclass and superclass possess same signatures. 6. Overriding is used in modifying the methods of the super class. 7. In overriding return types and constructor parameters of methods should match.

132 //Method Overriding class Room { void Room_Super() System.out.println("The Room Base is Displayed"); } class HallRoom extends Room System.out.println("The Sub Class Room Base is Displayed"); class MainRoom public static void main(String [] args) HallRoom br = new HallRoom(); br.Room_Super();

133 Super Keyword in Method Overriding
If your method overrides one of its super class's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). //Super keyword in Method Overriding class Room { void Room_Super() System.out.println("The Room Base is Displayed"); } class HallRoom extends Room System.out.println("The Sub Class Room Base is Displayed"); super.Room_Super(); class MainRoom public static void main(String [] args) HallRoom br = new HallRoom(); br.Room_Super();

134 Inheritance with Abstract Class

135 abstract type name (parameter – list)
Abstract Class You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the super class . Thus, a subclass must override them – it cannot simply use the version defined in the superclass. To declare an abstract method, use this general form: abstract type name (parameter – list) Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in from of the class keyword at the beginning of the class declaration. Conditions for the Abstract Class 1. We cannot use abstract classes to instantiate objects directly. For example. Shape s = new Shape(); is illegal because shape is an abstract class. 2. The abstract methods of an abstract class must be defined in its subclass. 3. We cannot declare abstract constructors or abstract static methods.

136 //Abstract Class Implementation
abstract class A { abstract void callme( ); // Abstract Method void callmetoo( ) // Concrete Method System.out.println("This is a Concrete method"); } class B extends A void callme( ) //Redefined for the Abstract Method System.out.println("B's Implementation of Callme"); class MainRoom public static void main(String [] args) B b = new B( ); b.callme( ); b.callmetoo( ); } }

137 Inheritance with final Keyword

138 What is the purpose of final keyword?
1. Can’t initialize to variable again and again (Equivalent to Constant) 2. Can’t Method Overriding 3. Can’t Inherited 1. Can’t initialize to variable again and again (Equivalent to Constant) class Final { public static void main(String args[]) final int a = 45; a = 78; //cannot assign the value to final Variable System.out.println("The A Value is:" + a); }

139 2. Can’t Method Overriding
class Super { final void Super_Method() System.out.println("This is Super Method"); } class Sub extends Super //Super method in sub cannot override Super_Method() in super; Overridden //method is final void Super_Method() System.out.println("This is Sub Method"); class Final public static void main(String args[]) Sub s = new Sub(); s.Super_Method();

140 3. Can’t Inherited final class Super { void Super_Method() System.out.println("This is Super Method"); } class Sub extends Super //cannot inherit from final super System.out.println("This is Sub Method"); class Final public static void main(String args[]) Sub s = new Sub(); s.Super_Method();

141 Interface

142 Why are you using Interface?
1. Java does not support multiple inheritances. That is, classes in java cannot have more than one superclass. For instances, 2. a is not permitted in Java. However, the designers of java could not overlook the importance of multiple inheritances. 3. A large number of real life applications require the use of multiple inheritances whereby we inherit methods and properties from several distinct classes. 4. Since C++ like implementation of multiple inheritances proves difficult and adds complexity to the language, Java provides an alternate approach known as interfaces to support the concept of multiple inheritances. 5. Although a java class cannot be a subclass or more than one superclass, it can implement more than one interface, thereby enabling us to create classes that build upon other classes without the problems created by multiple inheritances. class A extends B extends C { }

143 Defining Interfaces An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with major difference. The difference is that interfaces define only abstract methods and final fields. This means that interfaces do not specify any code to implement these methods and data fields contain only constants. Syntax: interface Interface_name { Variable declaration; Method declaration; } Ex: interface Item { static final int code = 1001; static final String name = “CCET”; void display (); } Ex: interface Area { final static float pi = 3.142F; float compute (float x,float y); void show(); }

144 How to Interface implements to the Classes
Syntax: class class_name implements interface_name { //Member of the Classes //Definition of the Interfaces } Ex: interface student { int slno = 12345; String name = "CCET"; void print_details(); } class Inter_Def implements student void print_details() System.out.println("The Serial Number is:" + slno); System.out.println("The Student name is:" + name);

145 Abstract classes Interfaces
Difference between Abstract Classes and Interfaces Abstract classes Interfaces Abstract classes are used only when there is a “is-a” type of relationship between the classes. Interfaces can be implemented by classes that are not related to one another. You cannot extend more than one abstract class. You can implement more than one interface. it contains both abstract methods and non Abstract Methods Interface contains all abstract methods Abstract class can implemented some methods also. Interfaces can not implement methods. With abstract classes, you are grabbing away each class’s individuality. With Interfaces, you are merely extending each class’s functionality.

146 Difference between Classes and Interfaces
Interface is little bit like a class... but interface is lack in instance variables....that's u can't create object for it. Interfaces are developed to support multiple inheritances. 3. The methods present in interfaces are pure abstract. 4. The access specifiers public, private, protected are possible with classes. But the interface uses only one spcifier public Interfaces contain only the method declarations.... no definitions 6. In Class the variable declaration as well as initialization, but interface only for initializing.

147 Types of Interfaces A B C A B C D E A B C Interface Implementation
Class Extension A B C D E Class Extension Interface Implementation A B C Interface Implementation Class

148 A B C D Interface Implementation Class Extension

149 // HIERARICHICAL INHERITANCE USING INTERFACE interface Area {
final static float pi = 3.14F; float compute (float x,float y); } class Rectangle implements Area public float compute(float x,float y) return (x * y); class Circle implements Area return (pi * x * x); A B C Interface Implementation Class

150 class InterfaceTest { public static void main(String args[]) Rectangle rect = new Rectangle (); Circle cir = new Circle(); Area area; //Interface object area = rect; System.out.println("Area of Rectangle = " + area.compute(10,20)); area = cir; System.out.println("Area of Circle = " + area.compute(10,0)); }

151 D //HYBRID INHERITANCE USING INTERFACES class Student {
int rollnumber; void getnumber(int n) rollnumber = n; } void putnumber() System.out.println("Roll No: " + rollnumber); class Test extends Student float part1, part2; void getmarks(float m1,float m2) part1 = m1; part2 = m2; void putmarks() System.out.println("Marks obtained"); System.out.println("Part1 = " + part1); System.out.println("Part2 = " + part2); A B C Interface Implementation Class Extension D

152 interface Sports { float sportwt = 6.0F; void putwt(); } class Results extends Test implements Sports float total; public void putwt() System.out.println("Sports Wt = " + sportwt); void display() total = part1 + part2 + sportwt; putnumber(); putmarks(); putwt(); System.out.println("Total Score = " + total);

153 class Hybrid { public static void main(String args[]) Results stud = new Results(); stud.getnumber(1234); stud.getmarks(27.5F, 33.0F); stud.display(); }

154 What is Partial Implementation?
The Interface is implementation to the Abstract class is called Partial Implementation. Example: interface Partial_Interface { public void display_one(); } abstract class Abstract_Class implements Partial_Interface public void display_one() //Definition for the Interface Method System.out.println("This is Interface Method"); void display_two() //Concrete Method System.out.println("This is Concrete Method"); abstract void display_three(); //Abstract Method

155 class Pure_Class extends Abstract_Class
{ void display_three() //Definition for the Abstract Method System.out.println("This is Abstract Method"); } class Final public static void main(String args[]) Pure_Class pc = new Pure_Class(); pc.display_one(); pc.display_two(); pc.display_three();

156 Package

157 What is Packages? Packages are java’s way of grouping a variety of classes and / or interfaces together. The grouping is usually done according to functionality. In fact, packages act as “containers” for classes. What are the benefits of Packages? 1. The classes contained in the packages of other programs can be easily reused. 2. In packages, classes can be unique compared with classes in other packages. That is, two classes in two different packages can have the same name. They may be referred by their fully qualified name, comprising the package name and class name. 3. Packaged provide a way to “hide classes thus preventing other programs or package from accessing classes that are meant for internal use only. 4. Packages also provide a way for separating “design” from “coding”. First we can design classes and decide their relationships, and then we can implement the java code needed for the methods. It is possible to change the implementation of any method without affecting the rest of the design.

158 Java packages are therefore classified into two types.
Types of Packages Java packages are therefore classified into two types. 1. Pre – defined packages (Java API Packages) 2. User – defined packages Java API Packages Package Name Contents java.lang Language support classes. These are classes that java compiler itself uses and therefore they are automatically imported. They include classes for primitive types, strings, math functions, threads and exceptions java.util Language utility classes such as vectors, hash tables, random numbers, date, etc. java.io Input / Output support classes. They provide facilities for the input and output of data. java.awt Set of classes for implementing graphical user interface. They include classes for windows, buttons, lists, menus and so on. java.net Classes for networking. They include classes for communicating with local computers as well as with internet servers. java.applet Classes for creating and implementing applets.

159 2. USER DEFINED PACKAGES How to Creating our own Packages
Creating our own package involves the following steps: 1. Declare the package at the beginning of a file using the form package package_name; 2. Define the class that is to be put in the package and declare it public 3. Create a subdirectory under the directory where the main source files are stored. 4. Store the listing as the classname.java file in the subdirectory created. 5. Compile the file. This creates .class file in the subdirectory. 6. The subdirectory name must match the package name exactly. Note: Java also supports the concept of package hierarchy. This done by specifying multiple names in a package statement, separated by dots. Example: package firstPackage.secondpackage;

160 Example: Create Package: package package1; public class ClassA { public void displayA() System.out.println("Class A"); } How to import the package: import package1.ClassA; class PackageTest1 { public static void main(String args[]) ClassA objectA = new ClassA() objectA.displayA(); }

161 ACCESS PROTECTION Access Modifier Access Location Public Protected
friendly (default) private protected private Same Class Yes Subclass in same package No Other classes in same package Subclass in other package Non – subclasses in other packages

162 Example program for the above Access Protection Tabular
Protection.java: package p1; public class Protection { int n = 1; private int n_pri = 2; protected int n_pro = 3; public int n_pub = 4; public Protection() System.out.println("base constructor"); System.out.println("n = " + n); System.out.println("n_pri = " + n_pri); System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); }

163 This is file Derived.java:
package p1; class Derived extends Protection { Derived() System.out.println("derived constructor"); System.out.println("n = " + n); //System.out.println("n_pri = " + n_pri); //Cannot Access because //accessing level is same class //in same package System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); }

164 This is file SamePackage.java:
package p1; class SamePackage { SamePackage() Protection p = new Protection(); System.out.println("same package constructor"); System.out.println("n = " + p.n); //System.out.println("n_pri = " + p.n_pri); //Cannot Access because //accessing level is same //class in same package System.out.println("n_pro = " + p.n_pro); System.out.println("n_pub = " + p.n_pub); }

165 This is file OtherPackage.java:
package p2; class Protection2 extends p1.Protection { Protection2() System.out.println("derived other package constructor"); // System.out.println("n = " + n); //Cannot Access because //accessing level is non – sub //class same class // System.out.println("n_pri = " + n_pri); //Cannot Access because //accessing level is same //class in same package System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); }

166 This is file OtherPackage.java:
package p2; class OtherPackage { OtherPackage() p1.Protection p = new p1.Protection(); System.out.println("other package constructor"); // System.out.println("n = " + p.n); // Cannot access because the // accessing level is non – sub // class in same package // System.out.println("n_pri = " + p.n_pri); // Cannot access // because the accessing // level is same class in // same package // System.out.println("n_pro = " + p.n_pro); // Cannot access // because the accessing // level is sub – class in // other package System.out.println("n_pub = " + p.n_pub); }


Download ppt "I – UNIT Procedure Oriented Programming"

Similar presentations


Ads by Google