Java OOPs Concepts PDF
Document Details
Tags
Summary
This document discusses fundamental concepts of object-oriented programming (OOP), specifically in the Java language. It explains concepts like objects, classes, inheritance, polymorphism, and their use in software development.
Full Transcript
**Java OOPs Concepts** **Object-Oriented Programming** is a paradigm that provides many concepts, such as **inheritance**, **data binding**, **polymorphism**, etc. **Some of the popular Object-Oriented languages are: ** - [Java](https://www.javatpoint.com/java-tutorial) - [C\#](https://www.j...
**Java OOPs Concepts** **Object-Oriented Programming** is a paradigm that provides many concepts, such as **inheritance**, **data binding**, **polymorphism**, etc. **Some of the popular Object-Oriented languages are: ** - [Java](https://www.javatpoint.com/java-tutorial) - [C\#](https://www.javatpoint.com/c-sharp-tutorial) - [PHP](https://www.javatpoint.com/php-tutorial) - [Python](https://www.javatpoint.com/python-tutorial) - [C++](https://www.javatpoint.com/cpp-tutorial) The main aim of object-oriented programming is to implement real-world entities, for example, object, classes, abstraction, inheritance, polymorphism, etc. **OOPs (Object-Oriented Programming System)** --------------------------------------------- **Procedural programming** is about writing procedures or methods that perform operations on the data, while **Object-Oriented Programming** is about creating objects that contain both data and methods. **Object-oriented programming** has several advantages over procedural programming: - OOP is faster and easier to execute - OOP provides a clear structure for the programs - OOP helps to keep the Java code DRY \"Don\'t Repeat Yourself\", and makes the code easier to maintain, modify and debug - OOP makes it possible to create full reusable applications with less code and shorter development time **Object** means a real-world entity such as a pen, chair, table, computer, watch, etc. **Object-Oriented Programming** is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts: - Object - Class - Inheritance - Polymorphism - Abstraction - Encapsulation Apart from these concepts, there are some other terms which are used in Object-Oriented design: - Coupling - Cohesion - Association - Aggregation - Composition **Object** ---------- Any entity that has state and behavior is known as an Object. For example, a chair, pen, table, keyboard, bike, person, etc. It can be physical or logical. An **Object** can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other\'s data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects. **Example:** A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc. **Class** --------- *Collection of objects* is called class. It is a logical entity. A class can also be defined as a blueprint from which you can create an individual object. Class doesn\'t consume any space. ### ### **Inheritance** *When one object acquires all the properties and behaviors of a parent object*, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism. ### **Polymorphism** If *one task is performed in different ways*, it is known as polymorphism. For example: to convince the customer differently, to draw something, for example, shape, triangle, rectangle, etc. In Java, we use method overloading and method overriding to achieve polymorphism. Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc. #### **Abstraction** *Hiding internal details and showing functionality* is known as abstraction. For example: phone call, we don\'t know the internal processing. In Java, we use abstract class and interface to achieve abstraction. ### **Encapsulation** *Binding (or wrapping) code and data together into a single unit are known as encapsulation*. For example, a capsule, it is wrapped with different medicines. A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here. ### **Coupling** Coupling refers to the knowledge or information or dependency of another class. It arises when classes are aware of each other. If a class has the details information of another class, there is strong coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a class, method, and field. You can use interfaces for the weaker coupling because there is no concrete implementation. ### **Cohesion** Cohesion refers to the level of a component which performs a single well-defined task. A single well-defined task is done by a highly cohesive method. The weakly cohesive method will split the task into separate parts. The java.io package is a highly cohesive package because it has I/O related classes and interface. However, the java.util package is a weakly cohesive package because it has unrelated classes and interfaces. ### **Association** Association represents the relationship between the objects. Here, one object can be associated with one object or many objects. There can be four types of association between the objects: - One to One - One to Many - Many to One, and - Many to Many Let\'s understand the relationship with real-time examples. For example, One country can have one prime minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP\'s can have one prime minister (many to one), and many ministers can have many departments (many to many). Association can be undirectional or bidirectional. ### **Aggregation** Aggregation is a way to achieve Association. Aggregation represents the relationship where one object contains other objects as a part of its state. It represents the weak relationship between objects. It is also termed as a *has-a* relationship in Java. Like, inheritance represents the *is-a* relationship. It is another way to reuse objects. ### **Composition** The composition is also a way to achieve Association. The composition represents the relationship where one object contains other objects as a part of its state. There is a strong relationship between the containing object and the dependent object. It is the state where containing objects do not have an independent existence. If you delete the parent object, all the child objects will be deleted automatically. **Advantage of OOPs over Procedure-oriented programming language** ------------------------------------------------------------------ 1. OOPs makes development and maintenance easier, whereas, in a procedure-oriented programming language, it is not easy to manage if code grows as project size increases. 2. OOPs provides data hiding, whereas, in a procedure-oriented programming language, global data can be accessed from anywhere. ![](media/image2.png) Figure: Data Representation in Procedure-Oriented Programming Figure: Data Representation in Object-Oriented Programming 3\) OOPs provides the ability to simulate real-world event much more effectively. We can provide the solution of real word problem if we are using the Object-Oriented Programming language. **What is the difference between an object-oriented programming language and object-based programming language?** ----------------------------------------------------------------------------------------------------------------- Object-based programming language follows all the features of OOPs except Inheritance. JavaScript and VBScript are examples of object-based programming languages. Java Naming Convention ====================== Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method, etc. But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by several Java communities such as Sun Microsystems and Netscape. All the classes, interfaces, packages, methods and fields of Java programming language are given according to the Java naming convention. If you fail to follow these conventions, it may generate confusion or erroneous code. **Advantage of Naming Conventions in Java** ------------------------------------------- By using standard Java naming conventions, you make your code easier to read for yourself and other programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what the code does. **Naming Conventions of the Different Identifiers** --------------------------------------------------- The following table shows the popular conventions used for the different identifiers. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- **Identifiers Type** **Naming Rules** **Examples** ---------------------- --------------------------------------------------------------------------------------------------------------------------------------- -------------------------------------- Class It should start with the uppercase letter.\ public class **Employee**\ It should be a noun such as Color, Button, System, Thread, etc.\ {\ Use appropriate words, instead of acronyms. //code snippet\ } Interface It should start with the uppercase letter.\ interface **Printable**\ It should be an adjective such as Runnable, Remote, ActionListener.\ {\ Use appropriate words, instead of acronyms. //code snippet\ } Method It should start with lowercase letter.\ class Employee\ It should be a verb such as main(), print(), println().\ {\ If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as actionPerformed(). // method\ void **draw()**\ {\ //code snippet\ }\ } Variable It should start with a lowercase letter such as id, name.\ class Employee\ It should not start with the special characters like & (ampersand), \$ (dollar), \_ (underscore).\ {\ If the name contains multiple words, start it with the lowercase letter followed by an uppercase letter such as firstName, lastName.\ // variable\ Avoid using one-character variables such as x, y, z. int **id**;\ //code snippet\ } Package It should be a lowercase letter such as java, lang.\ //package\ If the name contains multiple words, it should be separated by dots (.) such as java.util, java.lang. package **com.javatpoint;**\ class Employee\ {\ //code snippet\ } Constant It should be in uppercase letters such as RED, YELLOW.\ class Employee\ If the name contains multiple words, it should be separated by an underscore(\_) such as MAX\_PRIORITY.\ {\ It may contain digits but not as the first letter. //constant\ static final int **MIN\_AGE** = 18;\ //code snippet\ } ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- **CamelCase in Java naming conventions** ---------------------------------------- Java follows camel-case syntax for naming the class, interface, method, and variable. If the name is combined with two words, the second word will start with uppercase letter always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc. Objects and Classes in Java =========================== In object-oriented programming technique, we design a program using objects and classes. An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only. ### **What is an object in Java** An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system. An object has three characteristics: - **State:** represents the data (value) of an object. - **Behavior:** represents the behavior (functionality) of an object such as deposit, withdraw, etc. - **Identity:** An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely. Example: Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so writing is its behavior. **An object is an instance of a class.** A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class. **Object Definitions:** - An object is *a real-world entity*. - An object is *a runtime entity*. - The object is *an entity which has state and behavior*. - The object is *an instance of a class*. **What is a class in Java** --------------------------- A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can\'t be physical. A class in Java can contain: - **Fields** - **Methods** - **Constructors** - **Blocks** - **Nested class and interface** ![](media/image4.png) ### **Syntax to declare a class:** ### ### **Instance variable in Java** A variable which is created inside the class but outside the method is known as an instance variable. Instance variable doesn\'t get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable. ### **Method in Java** In Java, a method is like a function which is used to expose the behavior of an object. **Method in Java** is a collection of instructions that performs a specific task. It provides the reusability of code. A **method** is a block of code or collection of statements or a set of code grouped together to perform a certain task or operation. It is used to achieve the **reusability** of code. We write a method once and use it many times. We do not require to write code again and again. It also provides the **easy modification** and **readability** of code, just by adding or removing a chunk of code. The method is executed only when we call or invoke it. The most important method in Java is the **main()** method. If you want to read more about the main() method, go through the link . ### **Method Declaration** The method declaration provides information about method attributes, such as visibility, return-type, name, and arguments. It has six components that are known as **method header**, as we have shown in the following figure. **Method Signature:** Every method has a method signature. It is a part of the method declaration. It includes the **method name** and **parameter list**. **Access Specifier:** Access specifier or modifier is the access type of the method. It specifies the visibility of the method. Java provides **four** types of access specifier: - **Public:** The method is accessible by all classes when we use public specifier in our application. - **Private:** When we use a private access specifier, the method is accessible only in the classes in which it is defined. - **Protected:** When we use protected access specifier, the method is accessible within the same package or subclasses in a different package. - **Default:** When we do not use any access specifier in the method declaration, Java uses default access specifier by default. It is visible only from the same package only. - **Return Type:** Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword. - **Method Name:** It is a unique name that is used to define the name of a method. It must be corresponding to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method name must be **subtraction().** A method is invoked by its name. - **Parameter List:** It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank. - **Method Body:** It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces. **Naming a Method** ------------------- While defining a method, remember that the method name must be a **verb** and start with a **lowercase** letter. If the method name has more than two words, the first name must be a verb followed by adjective or noun. In the multi-word method name, the first letter of each word must be in **uppercase** except the first word. For example: **Single-word method name:** sum(), area() **Multi-word method name:** areaOfCircle(), stringComparision() It is also possible that a method has the same name as another method name in the same class, it is known as **method overloading**. **Types of Method** ------------------- There are two types of methods in Java: - Predefined Method - User-defined Method ### **Predefined Method** In Java, predefined methods are the method that is already defined in the Java class libraries is known as predefined methods. It is also known as the **standard library method** or **built-in method**. We can directly use these methods just by calling them in the program at any point. Some pre-defined methods are **length(), equals(), compareTo(), sqrt(),** etc. When we call any of the predefined methods in our program, a series of codes related to the corresponding method runs in the background that is already stored in the library. Each and every predefined method is defined inside a class. Such as **print()** method is defined in the **java.io.PrintStream** class. It prints the statement that we write inside the method. For example, **print(\"Java\")**, it prints Java on the console Let\'s see an example of the predefined method. **Demo.java** **Output:** The maximum number is: 9 In the above example, we have used three predefined methods **main(), print(),** and **max()**. We have used these methods directly without declaration because they are predefined. The print() method is a method of **PrintStream** class that prints the result on the console. The max() method is a method of the **Math** class that returns the greater of two numbers. We can also see the method signature of any predefined method by using the link . When we go through the link and see the max() method signature, we find the following: ![](media/image6.png) #### **Advantage of Method** - Code Reusability - Code Optimization In the above method signature, we see that the method signature has access specifier **public**, non-access modifier **static**, return type **int**, method name **max(),** parameter list **(int a, int b).** In the above example, instead of defining the method, we have just invoked the method. This is the advantage of a predefined method. It makes programming less complicated. Similarly, we can also see the method signature of the print() method. ### **User-defined Method** The method written by the user or programmer is known as **a user-defined** method. These methods are modified according to the requirement. ### **How to Create a User-defined Method** Let\'s create a user defined method that checks the number is even or odd. First, we will define the method. We have defined the above method named findevenodd(). It has a parameter **num** of type int. The method does not return any value that\'s why we have used void. The method body contains the steps to check the number is even or odd. If the number is even, it prints the number **is even**, else prints the number **is odd**. ### **How to Call or Invoke a User-defined Method** Once we have defined a method, it should be called. The calling of a method in a program is simple. When we call or invoke a user-defined method, the program control transfer to the called method. In the above code snippet, as soon as the compiler reaches at line **findEvenOdd(num),** the control transfer to the method and gives the output accordingly. Let\'s combine both snippets of codes in a single program and execute it. **EvenOdd.java** **Output 1:** Enter the number: 12 12 is even **Output 2:** Enter the number: 99 99 is odd Let\'s see another program that return a value to the calling method. In the following program, we have defined a method named **add()** that sum up the two numbers. It has two parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value of a and b, respectively. Therefore, the method adds the value of a and b and store it in the variable s and returns the sum. **Addition.java** **Output:** The sum of a and b is= 24 ### **Static Method** A method that has static keyword is known as static method. In other words, a method that belongs to a class rather than an instance of a class is known as a static method. We can also create a static method by using the keyword **static** before the method name. The main advantage of a static method is that we can call it without creating an object. It can access static data members and also change the value of it. It is used to create an instance method. It is invoked by using the class name. The best example of a static method is the **main()** method. ### **Example of static method** **Display.java** **Output:** It is an example of a static method. ### **Instance Method** The method of the class is known as an **instance method**. It is a **non-static** method defined in the class. Before calling or invoking the instance method, it is necessary to create an object of its class. Let\'s see an example of an instance method. **Output:** The sum is: 25 There are two types of instance method: - **Accessor Method** - **Mutator Method** **Accessor Method:** The method(s) that reads the instance variable(s) is known as the accessor method. We can easily identify it because the method is prefixed with the word **get**. It is also known as **getters**. It returns the value of the private field. It is used to get the value of the private field. **Example** **Mutator Method:** The method(s) read the instance variable(s) and also modify the values. We can easily identify it because the method is prefixed with the word **set**. It is also known as **setters** or **modifiers**. It does not return anything. It accepts a parameter of the same data type that depends on the field. It is used to set the value of the private field. **Example** ### **Example of accessor and mutator method** **Student.java** ### **Abstract Method** The method that does not has method body is known as abstract method. In other words, without an implementation is known as abstract method. It always declares in the **abstract class**. It means the class itself must be abstract if it has abstract method. To create an abstract method, we use the keyword **abstract**. **Syntax** **abstract** **void** method\_name(); ### **Example of abstract method** **Demo.java** **Output:** Abstract method\... ### **Factory method** It is a method that returns an object to the class to which it belongs. All static methods are factory methods. For example, **NumberFormat obj = NumberFormat.getNumberInstance();**