Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

SportyVampire6850

Uploaded by SportyVampire6850

Tags

object-oriented programming data structures software development

Full Transcript

OOPs OOPs → Object-Oriented Programming A programming paradigm based on the concept of classes and objects, which can contain data and code to manipulate that data. OOPs allows for more organized, modular, and reusable code, which is important whe...

OOPs OOPs → Object-Oriented Programming A programming paradigm based on the concept of classes and objects, which can contain data and code to manipulate that data. OOPs allows for more organized, modular, and reusable code, which is important when dealing with complex problems in Data Structures and Algorithms. 📌 Programming Paradigm: A fundamental style or approach to programming that dictates how developers write and organize code. It has a set of principles, concepts, and patterns that define how programs are constructed. Main programming paradigms are: 1. Imperative Programming → Focuses on explicitly describing the steps to achieve a desired outcome [C, Java] 2. Declarative Programming → Focuses on describing what the program should accomplish without specifying how to achieve it [SQL, HTML] 3. Object-Oriented Programming Advantages of OOPs Modularity: dividing programs into objects, making it easier to manage and modify. Reusability: through inheritance, existing code can be reused OOPs 1 Scalability: provides a clear structure for programs, making it easier to scale them as new features are added Maintainability: changes are confined to individual objects, minimizing the risk of affecting other parts of the program, increases maintainability. Abstraction: hiding the implementation details, simplifies complexity. Encapsulation: provides data hiding, increases security. Class and Objects Class Object It is a user defined data type that act as a An instance of class. template/ blueprint for creating objects It encapsulates data for the object and A real world entity that represents the methods to manipulate that data. specific instance of a class. Declared just once Can be declared as and when required No memory is allocated or action is It holds actual data in the form of attributes performed on class declaration until an and can perform actions using the object is created from that class. methods defined in the class. Example: Fruit is a class and Mango, Apple, Banana are objects Note: All the objects created of a particular class are completely independent from each other. Any changes done in one object will not reflect in others. Class Vs Struct Class Structure Collection of variables of different data Collection of objects types under a single unit Used to combine data and methods Used to grouping data together Class’s objects are created on heap Structure’s objects are created on the memory stack memory Class can inherit another class Structure can’t inherit another structure OOPs 2 Class Structure Structure has all members public by Class has all members private by default default Ideal for larger or complex objects Ideal for small and isolated model objects Basic Features of OOPs 1. Encapsulation 2. Abstraction 3. Inheritance 4. Polymorphism Encapsulation Bundling of data(variables) and methods(functions) into a single unit known as a class It declares variables as private restricting direct access to it from outside the class. Methods are declared as public so only the object's methods can access and modify data. Data Hiding: Encapsulation hides the internal details of how an object works. The object's data is kept private and can only be accessed or modified through methods (getters and setters). Controlled Access: Through encapsulation, only specific methods are provided to access or modify the data, ensuring more controlled and secure interactions with the object's data. Access Specifiers Access specifiers determine the visibility and accessibility of classes, methods, and variables. The most common access specifiers are: Public: accessible within or outside the class, package, subclasses. [highest level accessibility] OOPs 3 Private: accessible within the same class, not even in subclasses [lowest level accessibility] Protected: accessible from classes in the same package and subclasses (whether in same package or other) If no access specifier is used, a default specifier is assigned meaning the class or method is accessible only within its own package. Abstraction Hiding the complex implementation details & showing only the necessary features of an object. Hides Complexity: Abstraction allows a user to interact with an object or method without needing to understand the underlying details of how it works. Simplifies Interaction: Only the important aspects are exposed, making it easier to use the object or method. Example: A real-world example of abstraction is a car. A driver only interacts with the steering wheel and pedals without knowing how the engine works internally. Data abstraction is achieved by using Abstract class A class that cannot be instantiated directly. It’s a blueprint for other classes. It can have both abstract methods (methods without a body) and regular methods (methods with a body). Abstract methods are intended to be implemented by subclasses, ensuring that each subclass provides its own specific implementation of the method. It is declared with abstract keyword OOPs 4 A class can only inherit one abstract class abstract class Animal { // Abstract method (does not have a body) public abstract void makeSound(); // Non-abstract method public void sleep() { System.out.println("Sleeping..."); } } class Dog extends Animal { // Implementing the abstract method public void makeSound() { System.out.println("Bark"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.makeSound(); // Output: Bark dog.sleep(); // Output: Sleeping... } } Abstract Methods → methods which have only declaration not the implementation. implementation is done in derived classes. Interface An interface is a set of abstract methods that a class must implement It contains only abstract methods (prior to Java 8). From Java 8 onwards, interfaces can also contain default and static methods with implementation. OOPs 5 Interfaces cannot be instantiated. They only serve as a blueprint. A class can implement multiple interfaces, so allows multiple inheritance. Any class implementing an interface must provide implementations for all methods declared in the interface. interface Animal { void makeSound(); // abstract method void sleep(); // abstract method } class Dog implements Animal { public void makeSound() { System.out.println("Bark"); } public void sleep() { System.out.println("Sleeping..."); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.makeSound(); // Output: Bark dog.sleep(); // Output: Sleeping... } } Advantages of Abstraction with Interfaces: Multiple Inheritance: A class can implement multiple interfaces, unlike classes that can only extend one class. Loose Coupling: Interfaces help to reduce the dependencies between different parts of the code, making the system more modular and easier to maintain. OOPs 6 Difference between Abstract Classes & Interfaces Features Abstract Class Interface Multiple can only inherit one abstract can inherit multiple interfaces Inheritance class no access modifiers can be allows to assign access modifiers Access Modifiers assigned. all members are to its members public. Fields and Fields and constants can be Fields and constants cannot Constants defined be defined takes time to find the faster to access the implemented Performance members of the class member. corresponding class Inheritance Extending Functionality: The child class can add new features or override existing ones to modify the behavior inherited from the parent class. a class inherit properties and behaviors (fields and methods) from another class. It helps in reusing existing code and creating a hierarchical relationship between classes. parent/base/super-class → a class from which other classes are derived child/derived/sub-class → a class that is created from an existing class Types of Inheritance Single Inheritance → only one base class and one derived class Hierachial Inheritance → only one base class and many derived classes Multi-Level Inheritance → derived class is created from another derived class Multiple Inheritance → multiple base classes and only one derived class. Many high level languages like Java, C# doesn’t support this inheritance Hybrid Inheritance → combination of more than one type of inheritance OOPs 7 Why Java or C# don’t support multiple inheritance? Ambiguity Around The Diamond Problem suppose class A has two subclasses B and C, and a class D has two super classes B and C. If a method present in A is overridden by both B and C but not by D then from which class D will inherit that method B or C? This problem is known as diamond problem. Multiple inheritance does complicate the design and creates problem during casting, constructor chaining etc. Polymorphism ability of an object to take on many forms. It allows objects to be treated as instances of their parent class or interface, while having the ability to take on different forms or behaviors. It enables the same method to perform different actions depending on the object calling it. Types of Polymorphism Compile time Polymorphism (CTP) → static polymorphism or early binding The ability to have multiple methods in the same class with the same name but different parameters (number or type of parameters). achieved by method/function/operator overloading Overloading: When there are multiple entities with same name but different parameters then these entities are said to be overloaded. Entities can be overloaded by change in number/type of arguments OOPs 8 Runtime Polymorphism (RTP) → dynamic polymorphism or late binding. The ability of a subclass to provide a specific implementation of a method that is already defined in its parent class. achieved by method/function overriding Overriding: When a derived class has a definition for one of the method of the base class methods having same name which can have different functionalities That method is said to be overridden. Static Methods A static method belongs to the class rather than any instance of the class. OOPs 9 static keyword → allows to call the a method without creating an instance of the class. can be called directly using the class name without the need to create an object. do not use any instance variables of any object of the class they are defined in. can not be overridden. stored in heap space of the memory. particularly useful for utility/helper methods that perform tasks independent of an object's state. To access non-static methods, an object of the class must be created using the new keyword, followed by the class constructor. Virtual functions function or method used to override the behavior of the function in an inherited class with the same signature to achieve the polymorphism defined in the base class and overridden in the inherited class. function cannot be private, as the private functions cannot be overridden used to achieve runtime polymorphism Pure Virtual functions function which have no definition a virtual function that doesn't need implementation is called pure virtual function A pure virtual function have not definitions but we must override that function in the derived class, otherwise the derived class will also become abstract class. OOPs 10 Friend function A friend function is a friend of a class that is allowed to access to public, private, or protected data in that same class. If the function is defined outside the class, it cannot access such information. A friend can be declared anywhere in the class declaration, and it cannot be affected by access control keywords like private, public, or protected Constructor A constructor is a special type of method used to initialize objects. The constructor's main role is to set initial values for the object's attributes and perform any necessary setup tasks. Same Name as Class: A constructor has the same name as the class it belongs to. Called Automatically: When an object is created using the new keyword, the constructor is called automatically. No Return Type: Constructors do not have a return type, not even void. Types of Constructors: Default Constructor: A default constructor is a constructor that has no parameters. If no constructor is defined in a class, automatically a default constructor is provided that initializes object fields to their default values Parameterized Constructor: A parameterized constructor Types of Constructor Default constructor → constructor with 0 parameters Parameterized constructor → allows passing arguments to the constructor to assign specific values to object attributes Copy constructor → constructor which use existing object to create a new object OOPs 11 Static constructor → automatically called when the first instance is generated, explicitly declared by using a static keyword Private constructor → a constructor declared private. we cannot create an object of the class. Constructor Overloading A class can have multiple constructors, a concept known as constructor overloading. This allows the class to have different constructors with varying parameters. Each constructor can perform different initializations based on the number or type of arguments passed during object creation. Destructor special method which is used to destroy an object. called automatically when the object goes out of scope or is explicitly destroyed by a call to delete. has the same name as the class, preceded by a tilde (~). Shallow Copy & Deep Copy Shallow Copy Deep Copy A shallow copy creates a new object but A deep copy creates a completely new copies the references to the original object, along with new copies of all nested object's attributes. objects within it. The object is duplicated, but any nested The entire structure, including nested objects inside it are not; instead, they point objects, is duplicated, so the copied object to the same memory locations. is fully independent of the original. Changes made to nested objects in the Changes made in the deep copy will not shallow copy will reflect in the original affect the original object. object. OOPs 12 How does OOPs follow bottom-up approach? The bottom-up approach refers to building a system by first creating smaller, reusable components (like classes and objects) and then integrating them to form more complex systems. This approach contrasts with the top-down approach, where you start with a high-level design and break it down into smaller parts. In OOPs, the primary focus is on creating classes and objects that represent smaller components of a system. Each class is designed to model a specific entity or concept, with its own attributes and methods. These classes can be combined or extended to create more complex behaviors without modifying the original class, following a bottom-up process. OOP uses inheritance and composition to combine small classes into more complex structures. With encapsulation, individual objects manage their own state and behavior. This promotes a bottom-up approach because you focus on each object’s internals before integrating it into the larger system. Exception Handling A mechanism in programming to handle runtime errors, ensuring the normal flow of the program even when an error occurs. Instead of terminating the program abruptly, exceptions allow the program to catch and manage the error gracefully. Key Concepts of Exception Handling Exception: an event that disrupts the normal execution flow of a program. It usually occurs due to errors like division by zero, accessing an invalid OOPs 13 memory location, or file not found errors. Throwing an Exception: When an error is detected during execution, an exception is "thrown", meaning the system generates an error signal. Catching an Exception: To handle an exception, the program uses a try- catch block. If the code within the try block encounters an exception, it transfers control to the corresponding catch block. Basic Structure of Exception Handling: tryblock: Contains code that try { might throw an exception. catch block: Catches and handles } the exception. The type of catch (ExceptionType e) { exception that needs to be caught is specified in } parentheses. finally { finally block (Optional): Contains cleanup code that } always runs, regardless of whether an exception occurred or not. Common Exception Types: Divide by Zero: Attempting to divide a number by zero. Null Pointer Exception: Accessing an object through a null reference. Array Index Out of Bounds: Trying to access an array element outside its valid index. File Not Found: Trying to open a file that doesn't exist. Advantages Prevents program crashes by handling errors. OOPs 14 The main code logic is separated from error-handling code, making the program cleaner. Ensures that an error does not disrupt the program's flow. Disadvantages Performance Overhead: Exception handling may slightly slow down execution because of the overhead of checking and catching exceptions. Complexity: Excessive use of exceptions can make the code harder to understand. Disadvantages of OOPs Complexity: introduction of a lot of concepts like inheritance, polymorphism, abstraction, and encapsulation can be difficult to grasp for beginners Larger Memory Usage: objects in OOP consume more memory because each object carries data and methods Slower Execution: due to features like inheritance, and encapsulation, OOP can result in slower performance Overhead in Design: designing a well-structured OOP system requires careful planning and can take more time upfront. This can lead to delays in smaller projects. Not Always Suitable for All Problems: some problems don’t map well to the object-oriented paradigm Tightly Coupled Code: when classes are deeply interconnected via inheritance and composition, changes in one class can have a ripple effect, making the code harder to maintain and refactor. Requires More Effort for Simple Tasks: for small, straightforward applications, OOP can add unnecessary complexity, making it harder to implement compared to procedural programming. OOPs 15

Use Quizgecko on...
Browser
Browser