Unit-1 Introduction to Object Oriented Programming and Basic Concepts PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document introduces object-oriented programming concepts, specifically focusing on Java. It details programming languages, object-oriented programming, and related Java concepts like classes, objects, and inheritance.
Full Transcript
Unit-1 Introduction to Object oriented programming and Basic concept of Java Programming Languages Procedure oriented programming Object oriented programming Procedure oriented programming In POP, programs are divided into smaller programs known as functions. In POP, program is...
Unit-1 Introduction to Object oriented programming and Basic concept of Java Programming Languages Procedure oriented programming Object oriented programming Procedure oriented programming In POP, programs are divided into smaller programs known as functions. In POP, program is written as a sequence of procedures. Each procedure contains a series of instructions for performing a specific task. During the program execution each procedure can be called by the other procedure. The major emphasis of this language is on the procedure, not on the data. Structure of Procedure-oriented programming Relationship of data & functions in POP Characteristics of Procedure-oriented programming Large programs are divided into smaller programs Most of functions share global data Data move freely around the system from function to function. Functions transform data from one form to another. Top down approach is used for program design Object oriented programming Object-oriented programming is a methodology to design a program using Classes and objects. It ties data more closely to function that on it, and protects it from accidental modification from outside functions. OOP allows decomposition of a problem into a number of entities called objects and then build data functions around these objects. The data of an object can be accessed only by the functions associated with that object. Organization of data and functions in OOP Characteristics of OOP Emphasis is on data rather than procedure. Programs divided into objects. Functions that operate on the data of an object are tied together in the data structure. Data is hidden and can not accessed by external functions. Object may communicate with each other through functions. New data and functions can be added easily whenever necessary. Follow bottom up approach in program design. Object oriented programming concepts Classes Objects Data encapsulation Abstraction Inheritance Polymorphism Dynamic binding Message Passing Objects It is a basic unit of Object Oriented Programming and represents the real life entities that have their own properties and behaviors. An object consists of: – State : Represented by attributes of an object. – Behavior : Represented by methods of an object. – Identity : Gives a unique name to an object and enables one object to interact with other objects. Example of an object: person, table, dog etc. Objects Classes A class is the design or blueprint of any entity, which defines the core properties and functions. It represents the set of properties or methods that are common to all objects of one type. A class is a collection of objects of similar type. Encapsulation The wrapping up of data and functions into a single unit is called encapsulation. The data is not accessible to the outside world, only those functions which are wrapped in the class can access it. Abstraction – Essential element – Hiding of data – Its main goal is to hide unnecessary details from the user. – That enables the user to implement more complex logic on top of the provided abstraction without understanding or even thinking about all the hidden complexity. Inheritance Inheritance is the process by which objects of one class acquire the properties of objects of another class. It supports the concept of hierarchical classification. Each derived class shares common characteristics with the class from which it is derived. It provides the idea of reusability. Inheritance Polymorphism Ability to take more than one form Polymorphism refers to the ability of OOPs programming languages to differentiate between entities with the same name efficiently. This is done by Java with the help of the signature and declaration of these entities. Polymorphism are mainly of 2 types: – Overloading – Overriding Dynamic Binding Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance. Message passing Objects communicate with one another by sending and receiving information to each other. A message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired results. Message passing involves specifying the name of the object, the name of the function and the information to be sent. Benefits of Object oriented Programming Reuse of code through inheritance Flexibility through polymorphism We can build programs from the standard working module, no need of starting from the scratch. Effective problem solving Data hiding helps the programmer to build secure programs Multiple instances of an objects can co-exists with out any interference. It is easy to partition the work in a project based on objects. Object-oriented system can be easily upgraded from small to large systems. Message passing techniques for communication between objects makes the interface descriptions with external systems much simpler. Software complexity can be easily managed. Applications of Object oriented Programming Main application areas of OOP are: User interface design such as windows, menu. Real Time Systems Simulation and Modeling Object oriented databases AI and Expert System Neural Networks and parallel programming Decision support and office automation systems etc. Java history Initiated this project to develop a language for digital devices. Java technology later was incorporated by Netscape. Java language project was initiated by James Gosling, Patrick Naughton and Mike Sheridan in June 1991. It was called green talk and file extension was.gt. After that it was called oak and was developed as a part of green project. In 1995 oak was renamed as JAVA due to trademark issues by oak technologies. Java Features Simple Object-Oriented Portable Platform independent Secured Robust Architecture neutral High Performance Multithreaded Distributed Dynamic Simple Java is very easy to learn, and its syntax is simple, clean and easy to understand. Object-oriented Everything in Java is an object. Object-oriented means we organize our software as a combination of different types of objects that incorporates both data and behavior. Platform Independent Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform specific machines while Java is a write once, run anywhere language. Secured With Java, we can develop virus-free systems. Java is secured because: – No explicit pointer – Java Programs run inside a virtual machine sandbox Robust It uses strong memory management. There is a lack of pointers that avoids security problems. There is automatic garbage collection Architecture-neutral Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is fixed. Portable Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation. High-performance Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. Distributed Java is distributed because it facilitates users to create distributed applications in Java. This feature of Java makes us able to access files by calling the methods from any machine on the internet. Multi-threaded A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc. Dynamic Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++. Java supports dynamic compilation and automatic memory management (garbage collection). Compiling and Linking process in C Java Compile and Linking Process Byte code Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). JVM was designed as an interpreter for bytecode. JDK, JRE and JVM JVM- Java Virtual Machine JRE- Java Runtime Environment JDK- Java Development Kit JVM JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a Java program. When you run the Java program, Java compiler first compiles your Java code to bytecode. Then, the JVM translates bytecode into native machine code. Java is a platform-independent language. It's because when you write Java code, it's ultimately written for JVM but not your physical machine (computer). Since JVM executes the Java bytecode which is platform- independent, Java is platform-independent. Java Runtime Environment JRE (Java Runtime Environment) is a software package that provides Java class libraries, Java Virtual Machine (JVM), and other components that are required to run Java applications. Java Development Kit JDK is collection of classes, java compiler and JVM interpreter. JDK (Java Development Kit) is a software development kit required to develop applications in Java. When you download JDK, JRE is also downloaded with it. In addition to JRE, JDK also contains a number of development tools (compilers, JavaDoc, Java Debugger, etc). Relationship between JVM, JRE, and JDK Just In Time (JIT) In some cases JVM is slow. Bytecode must be interpreted at runtime. Java also provide local compiler that convert byte code into executable for faster running which is know as JIT. Setting Variable Environment Temporary: To set the temporary path of JDK, you need to follow the following steps: Open the command prompt Copy the path of the JDK/bin directory Write in command prompt: set path=copied_path set path=C:\Program Files\Java\jdk1.8.0_191\bin Permanent: For setting the permanent path of JDK, you need to follow these steps: Go to My Computer properties -> advanced tab -> environment variables -> new tab of system variable -> write path in variable name -> write path of bin folder in variable value -> ok 41 Hello World Java Program File must be saved as HelloWorld.java public class HelloWorld Main method from where execution will start { public static void main(String args[]) String must start with capital letter { System.out.println(“Hello World”); } System must start } with capital letter Data types in Java Primitive Data Types A primitive data type specifies the size and type of variable values, and it has no additional methods. Primitive types are predefined (already defined) in Java. A primitive type starts with a lowercase letter. Java defines 8 primitive types byte short int long char float double boolean Non-Primitive Data Types Non-primitive data types are called reference types because they refer to objects. Non-primitive types are created by the programmer and is not defined by Java (except for String). Non-primitive types can be used to call methods to perform certain operations. A primitive type has always a value, while non-primitive types can be null. Non-primitive types starts with an uppercase letter. Byte Smallest integer type It is a signed 8-bit type (1 Byte) Range is -128 to 127 Especially useful when working with stream of data from a network or file Default value = 0 Example: byte b = 10; Short short is signed 16-bit (2 Byte) type Range : -32768 to 32767 It is probably least used Java type Default value = 0 Example: short Id = 1234; Int The most commonly used type It is signed 32-bit (4 Byte) type Range: -2,147,483,648 to 2,147,483,647 Default value = 0 Example: int a = 34; Long long is signed 64-bit (8 Byte) type It is useful when int type is not large enough to hold the desired value Its value should be end with an "L“. Default value = 0L Example: long seconds = 1234124321L; Character The char data type is used to store a single character. It is 16-bit (2 Byte) type The character must be surrounded by single quotes Range: 0 to 65,536 Default value is ‘\u0000’. Example: – char first = ‘A’; – char second = 65; Float The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Its value should be end with "f“. It is 32-bit (4-Byte) type It specifies a single-precision value Default value = 0.0f Example: float price = 1234.45213f; output = 1123.4521 Double The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. should end the value with a "d“ It uses 64-bit (8-Byte) All math functions such as sin(), cos(), sqrt(), etc… returns double value Default value = 0.0d Example: double pi = 3.14141414141414d; boolean The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that track true/false conditions. The Boolean data type specifies one bit of information, but its "size" can't be defined precisely. Default Value = false Example: boolean a = true; String Literals Type Casting Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: 1. Widening Casting (automatic type casting) 2. Narrowing Casting (Explicit type casting) Automatic Type Casting Widening Casting (automatic type casting) - converting a smaller type to a larger type size Automatic type conversion will take place if the following two conditions are meet: The two types are compatible The destination type is larger than the source type byte -> short -> int -> long -> float -> double Explicit type casting Narrowing Casting (manually) - converting a larger type to a smaller size type To create a conversion between two incompatible types, you must use an explicit type conversion. double -> float -> long -> int -> short -> byte Syntax: (target-type) value Example: int a = 5; short b = (short) a; Type promotion in Expression While evaluating expressions, the intermediate value may exceed the range of operands and hence the expression value will be promoted. Some conditions for type promotion are: Java automatically promotes each byte, short, or char operand to int when evaluating an expression. If one operand is a long, float or double the whole expression is promoted to long, float or double respectively. For example: class Test { public static void main(String args[]) { byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = 1.1234; // The Expression double result = (f * b) + (i / c) - (d * s); //Result after all the promotions are done System.out.println("result = " + result); } } //In this, it will directly convert it into double as a larger data type. Explicit type casting in Expressions While evaluating expressions, the result is automatically updated to larger data type of the operand. But if we store that result in any smaller data type it generates compile time error, due to which we need to type cast the result. Example: class Test { public static void main(String args[]) { byte b = 50; //type casting int to byte b = (byte)(b * 2); System.out.println(b); } } Output: 100 Java Variables A variable is a container which holds the value while the java program is executed. A variable is assigned with a datatype. Variable is a name of memory location. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. Types of Variables There are three kind of variables in Java: – Local: A variable declared inside the body of the method is called local variable. You can use this variable only within that method. – Instance: A variable declared inside the class but outside the body of the method, is called instance variable. It is not declared as static. – Static: A variable which is declared as static is called static variable. It cannot be local. Memory allocation for static variable happens only once when the class is loaded in the memory. Local variables Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block. Access modifiers cannot be used for local variables. Local variables are visible only within the declared method, constructor or block. Local variables are implemented at stack level internally. There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use. Instance Variables Instance variables are declared in a class, but outside a method, constructor or any block. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. Instance variables have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor. Instance variables can be accessed directly by calling the variable name inside the class. Static variables The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students etc. The static variable gets memory only once in class area at the time of class loading. Advantage : It makes your program memory efficient (i.e it saves memory). Example without static variable class Student{ int rollNo; String name; String college=“CGPIT"; } Student class S1 S2 S3 Rollno = 101 Rollno = 102 Rollno = 103 Name = abc Name = xyz Name = bcd 69 College = CGPIT College = CGPIT College = CGPIT Example with static variable class Student{ int rollNo; String name; static String college=“CGPIT"; } Student class College = CGPIT S1 S2 S3 Rollno = 101 Rollno = 102 70 Rollno = 103 Name = abc Name = xyz Name = bcd Comments Comments in a program are called inline documentation They should be included to explain the purpose of the program and describe processing steps They do not affect how a program works Java comments can take three forms: // this comment runs to the end of the line Identifiers Identifiers are the words a programmer uses in a program An identifier can be made up of letters, digits, the underscore character ( _ ), and the dollar sign Identifiers cannot begin with a digit Java is case sensitive - Total, total, and TOTAL are different identifiers By convention, programmers use different case styles for different types of identifiers, such as – title case for class names - Lincoln – upper case for constants - MAXIMUM 1-72 Reserved Words The Java reserved words: abstract else interface switch assert enum long synchronized boolean extends native this break false new throw byte final null throws case finally package transient catch float private true char for protected try class goto public void const if return volatile continue implements short while default import static do instanceof strictfp double int super