├── Abstraction.md ├── Encapsulation.md ├── Images ├── DesignPatterns.png ├── Pillar-OOP.jpg ├── SOLID.jpg ├── abstraction.jpg ├── encapsulation.png ├── hierarchical-inheritance.jpg ├── hybrid-inheritance.png ├── inheritance.jpg ├── multilevel-Inheritance.png ├── multiple-inheritance.png ├── polymorphism.png └── single-Inheritance.png ├── Inheritance.md ├── Polymorphism.md └── README.md /Abstraction.md: -------------------------------------------------------------------------------- 1 | # Abstraction 2 | 3 | - In simple terms, abstraction “displays” only the relevant attributes of objects and “hides” the unnecessary details. 4 | 5 | - It is the process of hiding internal implementation details from the user and providing only necessary functionality to the users. It removes all non-essential things and shows only important things to users. 6 | 7 | For example, when we are driving a car, we are only concerned about driving the car like start/stop the car, accelerate/ break, etc. We are not concerned about how the actual start/stop mechanism or accelerate/brake process works internally. We are just not interested in those details. 8 | 9 | In other words, Abstraction in Java is a technique by which we can hide the data that is not required to a user 10 | 11 | Abstraction forces to use Inheritance 12 | 13 | Example 14 | 15 | We all use an ATM machine for cash withdrawal, money transfer, retrieve min-statement, etc in our daily life. But we don't know internally what things are happening inside ATM machine when you insert ATM card for performing any kind of operations. 16 | 17 | ## Abstraction in java 18 | 19 | There are two ways to achieve abstraction in java. They are as follows: 20 | * 1. Abstract class (0 to 100%) 21 | * 2. Interface (100%) 22 | 23 | ### Advantages 24 | 25 | **1**. It reduces the complexity of viewing the things. 26 | **2**. Avoids code duplication and increases reusability. 27 | **3**. Helps to increase security of an application or program as only important details are provided to the user. 28 | **4**. Programmer can implement abstract method to perform different tasks depending on the need. 29 | 30 | ### Abstract Class in Java 31 | An abstract class is a class, which is declared with `abstract` keyword. It is just like a normal class but has two differences. 32 | 33 | * 1. We cannot create an object of this class. Only objects of its non-abstract (or concrete) sub-classes can be created. 34 | 35 | * 2. It can have zero or more abstract methods which are not allowed in a non-abstract class (concrete class). 36 | 37 | :bulb: Key points: 38 | * 1. Abstract is a non-access modifier in java which is applicable for classes, interfaces, methods, and inner classes. It represents an incomplete class which depends on subclasses for its implementation. Creating subclass is compulsory for abstract class. 39 | - 2. A non-abstract class is sometimes called a concrete class. 40 | - 3. An abstract concept is not applicable to variables. 41 | 42 | ```An abstract class can have a data member, abstract method, method body (non-abstract method), constructor, and even main() method.``` 43 | 44 | ### Abstract Method in Java 45 | A method which is declared with abstract modifier and has no implementation (means no body) is called an abstract method in java. It does not contain any body. It has simply a signature declaration followed by a semicolon. It has the following general form as given below. 46 | 47 | Syntax: 48 | ```java 49 | abstract type MethodName(arguments); // No body
50 | ``` 51 | For example: 52 | ```java 53 | abstract void msg(); // No body.
54 | ``` 55 | Since the abstract method does not contain any body. Therefore, it is also known as an incomplete method in java. 56 | A non-abstract class cannot have an abstract method whether it is inherited or declared. In Java. 57 | 58 | :bulb: Key points: 59 | - 1. Abstract method cannot be static. 60 | - 2. It cannot be private because the abstract method must be implemented in the subclass. If we declare it as private, we cannot implement it from outside the class. 61 | - 3. A concrete method is a method which has always the body. It is also called a complete method in java. 62 | 63 | 64 | - Declares the existence of methods but not the implementation of those. 65 | - An abstract class defines behaviors that can vary due to polymorphism and that each explicit class that inherits from it must implement depending on its specific need. 66 | - You cannot have an instance of an abstract class 67 | - For a class to be abstract at least one of its methods must be abstract (this is the difference between a conventional class and an abstract class) 68 | - An abstract class cannot be instantiated but it can be inherited (Objects cannot be created directly with new) 69 | - Its use depends on the application of the concept of Inheritance 70 | - The first concrete subclass that inherits from an abstract class must implement all the superclass's methods 71 | - An abstract method does not define how it will behave since this logic is put in the classes that will implement the method 72 | 73 | An abstract class forces you to use inheritance 74 | 75 | Example Abstract class 76 | ```java 77 | abstract class Car{ 78 | abstract void run(); 79 | } 80 | 81 | class Honda extends Car{ 82 | void run(){ 83 | System.out.println("running safely"); 84 | } 85 | 86 | public static void main(String args[]){ 87 | Bike obj = new Honda4(); 88 | obj.run(); 89 | } 90 | } 91 | ``` 92 | 93 | Another example 94 | 95 | ```java 96 | //Example of an abstract class that has abstract and non-abstract methods 97 | abstract class Car{ 98 | Bike(){System.out.println("car is created");} 99 | abstract void run(); 100 | void changeGear(){ 101 | System.out.println("gear changed"); 102 | } 103 | } 104 | //Creating a Child class which inherits Abstract class 105 | class Honda extends Car{ 106 | void run(){ 107 | System.out.println("running safely"); 108 | } 109 | } 110 | //Creating a Test class which calls abstract and non-abstract methods 111 | class TestAbstraction2{ 112 | public static void main(String args[]){ 113 | Bike obj = new Honda(); 114 | obj.run(); 115 | obj.changeGear(); 116 | } 117 | } 118 | 119 | //RESULT 120 | bike is created 121 | running safely 122 | gear changed 123 | ``` 124 | 125 | ## Interface 126 | 127 | Another way to achieve abstraction in Java, is with interfaces. 128 | 129 | The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java. 130 | 131 | - It is an abstract class, that is, it cannot be instantiated 132 | - Since Java 8, we can have default and static methods in an interface. 133 | - Since Java 9, we can have private methods in an interface. 134 | - It has a list of methods that have no definition. So the methods are abstract (they have no functionality) 135 | - Java interface is a collection of abstract methods 136 | 137 | An ```interface``` is a completely "abstract class" that is used to group related methods with empty bodies: 138 | 139 | Example: 140 | 141 | ```java 142 | // Interface 143 | interface Animal { 144 | public void sound(); // interface method (does not have a body) 145 | public void sleep(); // interface method (does not have a body) 146 | } 147 | 148 | // Cat "implements" the Animal interface 149 | class Cat implements Animal { 150 | public void sound() { 151 | // The body of sound() is provided here 152 | System.out.println("The cat says: Miau"); 153 | } 154 | public void sleep() { 155 | // The body of sleep() is provided here 156 | System.out.println("Zzz"); 157 | } 158 | } 159 | 160 | class Main { 161 | public static void main(String[] args) { 162 | Cat myCat = new Cat(); // Create a Cat object 163 | myCat.animalSound(); 164 | myCat.sleep(); 165 | } 166 | } 167 | ``` 168 | 169 | ### Multiple Interfaces 170 | 171 | Example: 172 | 173 | ```java 174 | interface FirstInterface { 175 | public void myMethod(); // interface method 176 | } 177 | 178 | interface SecondInterface { 179 | public void myOtherMethod(); // interface method 180 | } 181 | 182 | class DemoClass implements FirstInterface, SecondInterface { 183 | public void myMethod() { 184 | System.out.println("Some text.."); 185 | } 186 | public void myOtherMethod() { 187 | System.out.println("Some other text..."); 188 | } 189 | } 190 | 191 | class Main { 192 | public static void main(String[] args) { 193 | DemoClass myObj = new DemoClass(); 194 | myObj.myMethod(); 195 | myObj.myOtherMethod(); 196 | } 197 | } 198 | ``` 199 | 200 | **About Information:** 201 | - Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an "Animal" object in the MyMainClass) 202 | - Interface methods do not have a body - the body is provided by the "implement" class 203 | - On implementation of an interface, you must override all of its methods 204 | - Interface methods are by default ```abstract``` and ```public``` 205 | - Interface attributes are by default ```public```, ```static``` and ```final``` 206 | - An interface cannot contain a constructor (as it cannot be used to create objects) 207 | 208 | **Why And When To Use Interfaces?** 209 | 210 | - To achieve security - hide certain details and only show the important details of an object (interface). 211 | - Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below). 212 | - It can be used to achieve loose coupling. 213 | 214 | 215 | **Java 8 interface** 216 | 217 | Since Java 8, interface can have default and static methods which is discussed later. 218 | 219 | The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static and final keywords before data members. 220 | 221 | In other words, Interface fields are public, static and final by default, and the methods are public and abstract. 222 | 223 | Print.java 224 | ```java 225 | inteface Print(){ 226 | int NUMBER = 5; 227 | voud print(); 228 | } 229 | ``` 230 | 231 | Compiler 232 | 233 | Print.class 234 | ```java 235 | interface Print(){ 236 | public static final int NUMBER = 5; 237 | public abstract void print(); 238 | 239 | } 240 | ``` 241 | 242 | ## The relationship between classes and interfaces 243 | 244 | As shown in the figure given below, a class extends another class, an interface extends another interface, but a class implements an interface. 245 | 246 | 247 |

248 | 249 |

250 | 251 | Example 252 | 253 | ```java 254 | interface Bank{ 255 | float rateOfInterest(); 256 | } 257 | class SBI implements Bank{ 258 | public float rateOfInterest(){return 9.15f;} 259 | } 260 | class PNB implements Bank{ 261 | public float rateOfInterest(){return 9.7f;} 262 | } 263 | class TestInterface2{ 264 | public static void main(String[] args){ 265 | Bank b=new SBI(); 266 | System.out.println("ROI: "+b.rateOfInterest()); 267 | }} 268 | ``` 269 | 270 | ## Multiple inheritance in Java by interface 271 | 272 | If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance. 273 | 274 |

275 | 276 |

277 | 278 | ```Multiple inheritance is not supported through class in java, but it is possible by an interface, why?``` 279 | 280 | As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class. For example: 281 | 282 | ```java 283 | interface Printable{ 284 | void print(); 285 | } 286 | interface Showable{ 287 | void print(); 288 | } 289 | 290 | class TestInterface3 implements Printable, Showable{ 291 | public void print(){System.out.println("Hello");} 292 | public static void main(String args[]){ 293 | TestInterface3 obj = new TestInterface3(); 294 | obj.print(); 295 | } 296 | } 297 | 298 | // RESULT 299 | Hello 300 | ``` 301 | 302 | 303 | ## Interface inheritance 304 | 305 | A class implements an interface, but one interface extends another interface. 306 | 307 | ```java 308 | interface Printable{ 309 | void print(); 310 | } 311 | interface Showable extends Printable{ 312 | void show(); 313 | } 314 | class TestInterface4 implements Showable{ 315 | public void print(){System.out.println("Hello");} 316 | public void show(){System.out.println("Welcome");} 317 | 318 | public static void main(String args[]){ 319 | TestInterface4 obj = new TestInterface4(); 320 | obj.print(); 321 | obj.show(); 322 | } 323 | } 324 | ``` 325 | 326 | ## Default Method in Interface 327 | 328 | ```java 329 | interface Drawable{ 330 | void draw(); 331 | default void msg(){System.out.println("default method");} 332 | } 333 | class Rectangle implements Drawable{ 334 | public void draw(){System.out.println("drawing rectangle");} 335 | } 336 | class TestInterfaceDefault{ 337 | public static void main(String args[]){ 338 | Drawable d=new Rectangle(); 339 | d.draw(); 340 | d.msg(); 341 | }} 342 | 343 | // RESULT 344 | drawing rectangle 345 | default method 346 | ``` 347 | 348 | ## Static Method in Interface 349 | 350 | Since Java 8, we can have static method in interface 351 | 352 | ```java 353 | interface Drawable{ 354 | void draw(); 355 | static int cube(int x){return x*x*x;} 356 | } 357 | class Rectangle implements Drawable{ 358 | public void draw(){System.out.println("drawing rectangle");} 359 | } 360 | 361 | class TestInterfaceStatic{ 362 | public static void main(String args[]){ 363 | Drawable d=new Rectangle(); 364 | d.draw(); 365 | System.out.println(Drawable.cube(3)); 366 | }} 367 | ``` 368 | 369 | ## Difference between abstract class and interface 370 | 371 | The main difference between interface and abstract class is that an interface provides an encapsulation mechanism for method protocols without forcing the user to use inheritance. 372 | 373 | But there are many differences between abstract class and interface that are given below. 374 | 375 | | Abstract class | Interface| 376 | |---|---| 377 | | Abstract class can have abstract and non-abstract methods. | Interface can have only abstract methods. Since Java 8, it can have default and static methods also.| 378 | | Abstract class doesn't support multiple inheritance. | Interface supports multiple inheritance.| 379 | | Abstract class can have final, non-final, static and non-static variables. | Interface has only static and final variables.| 380 | | Abstract class can provide the implementation of interface. | Interface can't provide the implementation of abstract class.| 381 | | The abstract keyword is used to declare abstract class. | The interface keyword is used to declare interface.| 382 | | An abstract class can extend another Java class and implement multiple Java interfaces. | An interface can extend another Java interface only.| 383 | | An abstract class can be extended using keyword "extends". | An interface can be implemented using keyword "implements".| 384 | | A Java abstract class can have class members like private, protected, etc. | Members of a Java interface are public by default.| 385 | | An abstract class can inherit from a single class (abstract or not) | interface can extend several interfaces at the same time. | 386 | | An abstract class can have methods that are or are not abstract | interfaces can only and exclusively define abstract methods or a default method | 387 | | In abstract classes the word abstract is mandatory to define an abstract method (as well as the class) | When you define an interface, this word is optional since it is inferred in the concept of interface.| 388 | | Abstract classes, unlike interfaces, can have constructors, default method implementations and can only be inherited once from these. | Although in java 8, default implementations are allowed, they cannot contain constructors. In the case of interfaces, if you can implement multiple of these | 389 | | abstract classes are more used for base type objects. It is like the parent in the hierarchy in a set of objects that share the same parent. | The interfaces are known as a contract. This is because they force you to implement their methods, which ensures all business logic that every object that implements it will have access to the methods defined in it. | 390 | | Abstract think more about objects | Interface think more about implementation | 391 | 392 | | parameters | Abstract class | Interface | 393 | |---|---|---| 394 | | keyword used | abstract | interface | 395 | | Type of variable | static and non-static | static | 396 | | Access modifiers | All access modifiers | Only public acces modifiers | 397 | | speed | Fast | Slow | 398 | | When to used | To avoid independence | For future Enhancement | 399 | 400 | 401 | Example: 402 | ```javapublic abstract class Shape{ 403 | public abstract void draw(); 404 | } 405 | ``` 406 | 407 | Example: 408 | ```java 409 | public interface Drawable{ 410 | void d 411 | aw(); 412 | } 413 | ``` 414 | 415 | Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%). 416 | 417 | Example of abstract class and interface 418 | 419 | ```java 420 | //Creating interface that has 4 methods 421 | interface A{ 422 | void a();// by default, public and abstract 423 | void b(); 424 | void c(); 425 | void d(); 426 | } 427 | 428 | //Creating abstract class that provides the implementation of one method of A interface 429 | abstract class B implements A{ 430 | public void c(){System.out.println("I am C");} 431 | } 432 | 433 | //Creating subclass of abstract class, now we need to provide the implementation of rest of the methods 434 | class M extends B{ 435 | public void a(){System.out.println("I am a");} 436 | public void b(){System.out.println("I am b");} 437 | public void d(){System.out.println("I am d");} 438 | } 439 | 440 | //Creating a test class that calls the methods of A interface 441 | class Test5{ 442 | public static void main(String args[]){ 443 | A a=new M(); 444 | a.a(); 445 | a.b(); 446 | a.c(); 447 | a.d(); 448 | } 449 | } 450 | ``` 451 | -------------------------------------------------------------------------------- /Encapsulation.md: -------------------------------------------------------------------------------- 1 | ## Encapsulation 2 | 3 | - “Encapsulation in Java can be defined as a mechanism using which the data and the methods that work on that data is wrapped to form a single unit.” 4 | 5 | - Using encapsulation we can also hide the class data members (variables) from the other classes. These data member variables can be accessed indirectly using methods of the class in which they are declared. The methods in turn are accessed using the object of that class. 6 | 7 | - Example (getters and setter methods) 8 | 9 | - We can visualize encapsulation as a medical capsule. As we all know the medicine is enclosed inside a medical capsule. Similarly, data and methods are enclosed in a single unit in encapsulation. 10 | 11 |

12 | 13 |

14 | 15 | - Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared. 16 | 17 | - As in encapsulation, the data in a class is hidden from other classes, so it is also known as **data-hiding**. 18 | 19 | - In other words, encapsulation is a programming technique that binds the class members (variables and methods) together and prevents them from being accessed by other classes. 20 | 21 | ## Encapsulation in java 22 | 23 | We can achieve encapsulation in Java in the following ways. 24 | 25 | - 1 Declaring the instance variable of the class as private. so that it cannot be accessed directly by anyone from outside the class. 26 | 27 | - 2 Provide the public setter and getter methods in the class to set/modify the values of the variable/fields. 28 | 29 | ### Advantages 30 | 31 | **1**. The encapsulated code is more flexible and easy to change with new requirements.
32 | **2**. It prevents the other classes to access the private fields.
33 | **3**. Encapsulation allows modifying implemented code without breaking others code who have implemented the code.
34 | **4**. It keeps the data and codes safe from external inheritance. Thus, Encapsulation helps to achieve security.
35 | **5**. It improves the maintainability of the application.
36 | **6**. If you don't define the setter method in the class then the fields can be made read-only.
37 | **7**. If you don't define the getter method in the class then the fields can be made write-only
38 | 39 | ### Disavantages 40 | The main disadvantage of the encapsulation in Java is it increases the length of the code and slow shutdown execution. 41 | 42 | ### Tightly Encapsulated Class 43 | If each variable is declared as private in the class, it is called tightly encapsulated class in Java. For tightly encapsulated class, we are not required to check whether class contains getter and setter method or not and whether these methods are declared as public or not. 44 | 45 | :bulb: **Key points:**
46 | **1**. It is highly recommended to declare data members as private in the class.
47 | **2**. A combination of data hiding and abstraction is nothing but encapsulation. 48 | Encapsulation = Data Hiding + Abstraction
49 | If any component follows data hiding and abstraction, it is called an encapsulated component. 50 | 51 | 52 | ## **Why Do We Need Encapsulation** 53 | 54 | **There are various reasons as to why encapsulation is essential in Java:** 55 | 56 | - Encapsulation allows us to modify the code or A part of the code without having to change any other functions or code. 57 | - Encapsulation controls how we access data. 58 | - We can modify the code based on the requirements using encapsulation. 59 | - Encapsulation makes our applications simpler. -------------------------------------------------------------------------------- /Images/DesignPatterns.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alejoalvarez/oop/22312b1d1215ec85c0d39a25ec9014ff05decfa9/Images/DesignPatterns.png -------------------------------------------------------------------------------- /Images/Pillar-OOP.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alejoalvarez/oop/22312b1d1215ec85c0d39a25ec9014ff05decfa9/Images/Pillar-OOP.jpg -------------------------------------------------------------------------------- /Images/SOLID.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alejoalvarez/oop/22312b1d1215ec85c0d39a25ec9014ff05decfa9/Images/SOLID.jpg -------------------------------------------------------------------------------- /Images/abstraction.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alejoalvarez/oop/22312b1d1215ec85c0d39a25ec9014ff05decfa9/Images/abstraction.jpg -------------------------------------------------------------------------------- /Images/encapsulation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alejoalvarez/oop/22312b1d1215ec85c0d39a25ec9014ff05decfa9/Images/encapsulation.png -------------------------------------------------------------------------------- /Images/hierarchical-inheritance.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alejoalvarez/oop/22312b1d1215ec85c0d39a25ec9014ff05decfa9/Images/hierarchical-inheritance.jpg -------------------------------------------------------------------------------- /Images/hybrid-inheritance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alejoalvarez/oop/22312b1d1215ec85c0d39a25ec9014ff05decfa9/Images/hybrid-inheritance.png -------------------------------------------------------------------------------- /Images/inheritance.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alejoalvarez/oop/22312b1d1215ec85c0d39a25ec9014ff05decfa9/Images/inheritance.jpg -------------------------------------------------------------------------------- /Images/multilevel-Inheritance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alejoalvarez/oop/22312b1d1215ec85c0d39a25ec9014ff05decfa9/Images/multilevel-Inheritance.png -------------------------------------------------------------------------------- /Images/multiple-inheritance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alejoalvarez/oop/22312b1d1215ec85c0d39a25ec9014ff05decfa9/Images/multiple-inheritance.png -------------------------------------------------------------------------------- /Images/polymorphism.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alejoalvarez/oop/22312b1d1215ec85c0d39a25ec9014ff05decfa9/Images/polymorphism.png -------------------------------------------------------------------------------- /Images/single-Inheritance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alejoalvarez/oop/22312b1d1215ec85c0d39a25ec9014ff05decfa9/Images/single-Inheritance.png -------------------------------------------------------------------------------- /Inheritance.md: -------------------------------------------------------------------------------- 1 | 2 | # Table of Contents 3 | 1. [Inheritance](#Inheritance) 4 | 2. [Type of inheritance](#type-inheritance) 5 | - [Single Inheritance](#single-inheritance) 6 | - [Multiple Inheritance](#multiple-inheritance) 7 | - [Multilevel Inheritance](#multilevel-inheritance) 8 | - [Hierarchical Inheritance](#hierarchical-inheritance) 9 | - [Hybrid Inheritance](#hybrid-inheritance) 10 | 3. [Aggregation](#aggregation) 11 | 12 | 13 | ## Inheritance 14 | Inheritance is the mechanism by which an object acquires the some/all properties of another object. 15 | 16 | The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. 17 | 18 | In Oriented Object Programming, the computer programs are designed in such a way where everything is an object that interacts with one another object. It basically, helps in reusing the code and establish a relationship between different classes. 19 | 20 | **Why use inheritance in java** 21 | - For Method Overriding (so runtime polymorphism can be achieved). 22 | - For Code Reusability. 23 | 24 | Terms: 25 | - **Class**: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. 26 | - **Sub Class/Child Class**: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. 27 | - **Super Class/Parent Class**: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. 28 | - **Reusability**: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. 29 | 30 | Syntax: 31 | ```java 32 | class Subclass-name extends SuperclassName{ 33 | //methods and fields 34 | } 35 | ``` 36 | 37 | ```java 38 | class Employee{ 39 | float salary=40000; 40 | } 41 | 42 | class Programmer extends Employee{ 43 | 44 | int bonus = 10000; 45 | 46 | public static void main(String args[]){ 47 | Programmer p = new Programmer(); 48 | System.out.println("Programmer salary is: " + p.salary); 49 | System.out.println("Bonus of Programmer is: " + p.bonus); 50 | } 51 | } 52 | ``` 53 | 54 |

55 | 56 |

57 | 58 | ## Types of Inheritance 59 | ### Single Inheritance 60 | 61 | In single inheritance, one class inherits the properties of another. It enables a derived class to inherit the properties and behavior from a single parent class. This will, in turn, enable code reusability as well as add new features to the existing code. 62 | 63 | When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance. 64 | 65 | ```java 66 | class Animal{ 67 | void eat(){ 68 | System.out.println("eating..."); 69 | } 70 | } 71 | 72 | class Dog extends Animal{ 73 | void bark(){ 74 | System.out.println("barking..."); 75 | } 76 | } 77 | 78 | class TestInheritance{ 79 | public static void main(String args[]){ 80 | Dog d=new Dog(); 81 | d.bark(); 82 | d.eat(); 83 | } 84 | } 85 | ``` 86 | 87 | ``` 88 | Output: 89 | barking... 90 | eating.. 91 | ``` 92 | 93 |

94 | 95 |

96 | 97 | Here, Class A is your parent class and Class B is your child class which inherits the properties and behavior of the parent class 98 | 99 | ### Multiple Inheritance 100 | 101 | To reduce the complexity and simplify the language, multiple inheritance is not supported in java. 102 | 103 | ```java 104 | class A{ 105 | oid msg(){ 106 | System.out.println("Hello"); 107 | } 108 | } 109 | class B{ 110 | void msg(){ 111 | System.out.println("Welcome"); 112 | } 113 | } 114 | class C extends A,B{ 115 | 116 | public static void main(String args[]){ 117 | C obj=new C(); 118 | obj.msg();//Now which msg() method would be invoked? 119 | } 120 | } 121 | 122 | ``` 123 | 124 | ``` 125 | Output: 126 | 127 | compile time error 128 | ``` 129 | 130 |

131 | 132 |

133 | 134 | ### Multilevel Inheritance 135 | When a class is derived from a class which is also derived from another class, i.e. a class having more than one parent class but at different levels, such type of inheritance is called Multilevel Inheritance. 136 | 137 | When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance. 138 | 139 | ```java 140 | class Animal{ 141 | void eat(){ 142 | System.out.println("eating..."); 143 | } 144 | } 145 | 146 | class Dog extends Animal{ 147 | void bark(){System.out.println("barking...");} 148 | } 149 | 150 | class BabyDog extends Dog{ 151 | void weep(){System.out.println("weeping...");} 152 | } 153 | 154 | class TestInheritance2{ 155 | public static void main(String args[]){ 156 | BabyDog d=new BabyDog(); 157 | d.weep(); 158 | d.bark(); 159 | d.eat(); 160 | } 161 | } 162 | 163 | ``` 164 | 165 | ``` 166 | Output: 167 | 168 | weeping... 169 | barking... 170 | eating... 171 | ``` 172 | 173 |

174 | 175 |

176 | 177 | If we talk about the flowchart, class B inherits the properties and behavior of class A and class C inherits the properties of class B. Here A is the parent class for B and class B is the parent class for C. So in this case class C implicitly inherits the properties and methods of class A along with Class B. That’s what is multilevel inheritance. 178 | 179 | ### Hierarchical Inheritance 180 | When a class has more than one child classes (subclasses) or in other words, more than one child classes have the same parent class 181 | 182 | When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance. 183 | 184 | ```java 185 | class Animal{ 186 | void eat(){ 187 | System.out.println("eating..."); 188 | } 189 | } 190 | class Dog extends Animal{ 191 | void bark(){ 192 | System.out.println("barking..."); 193 | } 194 | } 195 | class Cat extends Animal{ 196 | void meow(){ 197 | System.out.println("meowing..."); 198 | } 199 | } 200 | class TestInheritance3{ 201 | public static void main(String args[]){ 202 | Cat c=new Cat(); 203 | c.meow(); 204 | c.eat(); 205 | //c.bark();//Compile Time Error 206 | } 207 | } 208 | 209 | ``` 210 | 211 | ``` 212 | Output: 213 | 214 | meowing... 215 | eating... 216 | ``` 217 | 218 |

219 | 220 |

221 | 222 | ### Hybrid Inheritance 223 | Hybrid inheritance is a combination of two or more types of inheritance. 224 | 225 |

226 | 227 |

228 | 229 | 230 | ## Aggregation 231 | 232 | If a class have an entity reference, it is known as Aggregation 233 | 234 | Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own information such as city, state, country, zipcode etc. as given below. 235 | 236 | ```java 237 | class Employee{ 238 | int id; 239 | String name; 240 | Address address;//Address is a class 241 | ... 242 | } 243 | ``` 244 | 245 | In such case, Employee has an entity reference address, so relationship is Employee HAS-A address. 246 | 247 | ```java 248 | class Operation{ 249 | int square(int n){ 250 | return n * n; 251 | } 252 | } 253 | 254 | class Circle{ 255 | Operation op; //aggregation 256 | double pi = 3.14; 257 | 258 | double area(int radius){ 259 | op = new Operation(); 260 | int rsquare = op.square(radius);//code reusability (i.e. delegates the method call). 261 | return pi * rsquare; 262 | } 263 | 264 | 265 | 266 | public static void main(String args[]){ 267 | Circle c=new Circle(); 268 | double result=c.area(5); 269 | System.out.println(result); 270 | } 271 | } 272 | ``` 273 | 274 | Real example 275 | 276 | ```java 277 | public class Address { 278 | String city,state,country; 279 | 280 | public Address(String city, String state, String country) { 281 | this.city = city; 282 | this.state = state; 283 | this.country = country; 284 | } 285 | } 286 | ``` 287 | 288 | ```java 289 | public class Employee { 290 | int id; 291 | String name; 292 | Address address; 293 | 294 | public Employee(int id, String name,Address address) { 295 | this.id = id; 296 | this.name = name; 297 | this.address=address; 298 | } 299 | 300 | void printInformation(){ 301 | System.out.println(id+" "+name); 302 | System.out.println(address.city+" "+address.state+" "+address.country); 303 | } 304 | 305 | public static void main(String[] args) { 306 | Address address1=new Address("id1","name1","address1"); 307 | Address address2=new Address("id1","name2","address2"); 308 | 309 | Employee employee1=new Employee(111,"Alejo 1",address1); 310 | Employee employee2=new Employee(222,"Alejo 2",address2); 311 | 312 | employee1.printInformation(); 313 | employee2.printInformation(); 314 | 315 | } 316 | } 317 | ``` 318 | 319 | -------------------------------------------------------------------------------- /Polymorphism.md: -------------------------------------------------------------------------------- 1 | ## Polymorphism 2 | 3 | ![](https://github.com/Alejo-Alvarezv/OOP/blob/master/Images/polymorphism.png) 4 | 5 | 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. 6 | 7 | Polymorphism in Java are mainly of 2 types: 8 | 9 | ### Overloading (Compile time Polymorphism) 10 | 11 | Overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters or both. Overloading is related to compile-time (or static) polymorphism. 12 | 13 | It is also known as static polymorphism. This type of polymorphism is achieved by function overloading or operator overloading. 14 | 15 | Method Overloading: When there are multiple functions with same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type of arguments. 16 | 17 | Operator Overloading: Java also provide option to overload operators. For example, we can make the operator (‘+’) for string class to concatenate two strings. We know that this is the addition operator whose task is to add two operands. So a single operator ‘+’ when placed between integer operands, adds them and when placed between string operands, concatenates them. 18 | In java, Only “+” operator can be overloaded: 19 | 20 | - To add integers 21 | - To concatenate strings 22 | 23 | 24 | There are two ways to overload the method in java 25 | 26 | - By changing number of arguments 27 | - By changing the data type 28 | 29 | 30 | **Method Overloading: changing no. of arguments** 31 | 32 | 33 | ### Overriding (Runtime Polymorphism) 34 | It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding. 35 | 36 | Method overriding, on the other hand, occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden. 37 | 38 | In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. 39 | 40 | In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding. 41 | 42 | Usage 43 | - Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. 44 | - Method overriding is used for runtime polymorphism 45 | 46 | Rules 47 | - The method must have the same name as in the parent class 48 | - The method must have the same parameter as in the parent class. 49 | - There must be an IS-A relationship (inheritance). 50 | 51 | Example 52 | ```java 53 | class Vehicle{ 54 | //defining a method 55 | void run(){ 56 | System.out.println("Vehicle is running"); 57 | } 58 | } 59 | 60 | class Bike2 extends Vehicle{ 61 | void run(){ 62 | System.out.println("Bike is running"); 63 | } 64 | 65 | public static void main(String args[]){ 66 | Bike2 obj = new Bike2(); 67 | obj.run(); 68 | } 69 | } 70 | 71 | ``` 72 | 73 | ``` 74 | Output: 75 | 76 | Bike is running 77 | ``` 78 | 79 | Can we override static method? 80 | No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later, It is because the static method is bound with class whereas instance method is bound with an object. Static belongs to the class area, and an instance belongs to the heap area. 81 | 82 | | Parameter | Method Overloading | Method Overriding | 83 | |---|---|---| 84 | | Polymorphism | Method Overloading is used to implement Compile time or static polymorphism. | Method Overriding is used to implement Runtime or dynamic polymorphism.| 85 | | Purpose| It is used to expand the readability of the program. | It is used to give the specific implementation of the method which is already provided by its base class| 86 | | Parameter List | Parameters of the overloaded function must be different in either number or type in case of method overloading | The number of parameters and type of each parameter must be the same in case of method overriding.| 87 | | Number of Classes | It occurs within the same class | It is performed within two classes with an inheritance relationship.| 88 | | Inheritance | It may or may not be required for Method Overloading | It is must for Method Overriding | 89 | | Return Type | The return type may or may not be the same, but we have to change the parameter. | Here, the return type must be either the same or of the covariant type.| 90 | |static, final and private methods | We can overload a static, final or private method in Method Overloading | We can not override a static, final or private method in Method Overriding| 91 | | Bond | Static Binding Dynamic Binding | 92 | | Speed | It is fast | It is slower | 93 | | Signature | The signature must be different | The signature must be the same | 94 | | Association | It is usually associated with static programs. | It is usually associated with object-oriented programs.| 95 | | Performance Overloading gives better performance than overriding | Lesser Performance than Overloading because the binding of the overridden method is done at the runtime.| 96 | | Access Modifier Any access modifier can be used while overloading the methods | The level of access should be either the same or with a wider scope. | 97 | | Exceptions | May throw different exceptions. | May reduce or eliminate exceptions. But, must not throw new or broader checked exceptions but can throw narrower checked exceptions.| 98 | 99 | ## super 100 | 101 | The super keyword in Java is a reference variable which is used to refer immediate parent class object. 102 | 103 | Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable. 104 | 105 | Usage 106 | - **super** can be used to refer immediate parent class instance variable. 107 | - **super** can be used to invoke immediate parent class method. 108 | - **super()** can be used to invoke immediate parent class constructor. 109 | 110 | **(super) used to refer immediate parent class instance variable.** 111 | 112 | We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields. 113 | 114 | ```java 115 | class Animal{ 116 | String color="white"; 117 | } 118 | 119 | class Dog extends Animal{ 120 | String color="black"; 121 | void printColor(){ 122 | System.out.println(color);//prints color of Dog class 123 | System.out.println(super.color);//prints color of Animal class 124 | } 125 | } 126 | 127 | class TestSuper1 { 128 | public static void main(String args[]){ 129 | Dog d=new Dog(); 130 | d.printColor(); 131 | } 132 | } 133 | ``` 134 | 135 | ``` 136 | Output: 137 | 138 | black 139 | white 140 | ``` 141 | 142 | In the above example, Animal and Dog both classes have a common property color. If we print color property, it will print the color of current class by default. To access the parent property, we need to use super keyword. 143 | 144 | **(super) can be used to invoke parent class method** 145 | 146 | The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden. 147 | 148 | ```java 149 | class Animal{ 150 | void eat(){System.out.println("eating...");} 151 | } 152 | 153 | class Dog extends Animal{ 154 | void eat(){System.out.println("eating bread...");} 155 | void bark(){System.out.println("barking...");} 156 | void work(){ 157 | super.eat(); 158 | bark(); 159 | } 160 | 161 | } 162 | 163 | class TestSuper2{ 164 | public static void main(String args[]){ 165 | Dog d=new Dog(); 166 | d.work(); 167 | } 168 | } 169 | ``` 170 | 171 | ``` 172 | Output: 173 | 174 | eating... 175 | barking... 176 | ``` 177 | 178 | In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog class, it will call the eat() method of Dog class by default because priority is given to local. 179 | 180 | To call the parent class method, we need to use super keyword. 181 | 182 | **(super) is used to invoke parent class constructor.** 183 | 184 | ```java 185 | class Animal{ 186 | Animal(){System.out.println("animal is created");} 187 | } 188 | 189 | class Dog extends Animal{ 190 | Dog(){ 191 | super(); 192 | System.out.println("dog is created"); 193 | } 194 | } 195 | 196 | class TestSuper3{ 197 | public static void main(String args[]){ 198 | Dog d = new Dog(); 199 | } 200 | } 201 | 202 | ``` 203 | 204 | ``` 205 | Output: 206 | 207 | animal is created 208 | dog is created 209 | ``` 210 | 211 | ```IMPORTANT``` => super() is added in each class constructor automatically by compiler if there is no super() or this(). 212 | 213 | Real example 214 | ```java 215 | class Person{ 216 | int id; 217 | String name; 218 | 219 | Person(int id,String name){ 220 | this.id=id; 221 | this.name=name; 222 | } 223 | } 224 | class Emp extends Person{ 225 | float salary; 226 | Emp(int id,String name,float salary){ 227 | super(id,name);//reusing parent constructor 228 | this.salary = salary; 229 | } 230 | void display(){ 231 | System.out.println(id + " " + name + " " + salary); 232 | } 233 | } 234 | 235 | class TestSuper5{ 236 | public static void main(String[] args){ 237 | Emp e1 = new Emp(1,"alejo",45000f); 238 | e1.display(); 239 | } 240 | } 241 | 242 | ``` 243 | 244 | ``` 245 | Output: 246 | 247 | 1 alejo 45000 248 | ``` 249 | 250 | ## Instance initializer block 251 | 252 | Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created. 253 | The initialization of the instance variable can be done directly but there can be performed extra operations while initializing the instance variable in the instance initializer block. 254 | 255 | Example 256 | ```java 257 | class Bike{ 258 | int speed; 259 | 260 | Bike(){ 261 | System.out.println("speed is " + speed); 262 | } 263 | 264 | { 265 | speed=100; 266 | } 267 | 268 | public static void main(String args[]){ 269 | Bike7 bike1=new Bike(); 270 | Bike7 bike2=new Bike(); 271 | } 272 | } 273 | 274 | ``` 275 | 276 | ``` 277 | Output: 278 | 279 | speed is 100 280 | speed is 100 281 | ``` 282 | 283 | 284 | There are three places in java where you can perform operations: 285 | - method 286 | - constructor 287 | - block 288 | 289 | What is invoked first, instance initializer block or constructor? 290 | 291 | ```java 292 | class Bike{ 293 | int speed; 294 | 295 | Bike(){ 296 | System.out.println("constructor is invoked"); 297 | } 298 | 299 | { 300 | System.out.println("instance initializer block invoked"); 301 | } 302 | 303 | public static void main(String args[]){ 304 | Bike bike1=new Bike(); 305 | Bike bike2=new Bike(); 306 | } 307 | } 308 | 309 | ``` 310 | 311 | ``` 312 | Output: 313 | 314 | instance initializer block invoked 315 | constructor is invoked 316 | instance initializer block invoked 317 | constructor is invoked 318 | ``` 319 | 320 | In the above example, it seems that instance initializer block is firstly invoked but NO. Instance initializer block is invoked at the time of object creation. The java compiler copies the instance initializer block in the constructor after the first statement super(). So firstly, constructor is invoked 321 | 322 | ```Important``` => The java compiler copies the code of instance initializer block in every constructor. 323 | 324 | ```java 325 | class X{ 326 | 327 | X(){ 328 | System.out.println("constructor"); 329 | } 330 | 331 | { 332 | System.out.println("instance initializer block invoked"); 333 | } 334 | } 335 | ``` 336 | 337 | compiler 338 | 339 | ```java 340 | class X{ 341 | 342 | X(){ 343 | super(); 344 | { 345 | System.out.println("instance initializer block invoked"); 346 | } 347 | System.out.println("constructor"); 348 | } 349 | } 350 | ``` 351 | 352 | **Rules** 353 | 354 | - There are mainly three rules for the instance initializer block. They are as follows: 355 | - The instance initializer block is created when instance of the class is created. 356 | - The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call). 357 | - The instance initializer block comes in the order in which they appear. 358 | 359 | Example: Program of instance initializer block that is invoked after super() 360 | 361 | ```java 362 | class A{ 363 | A(){ 364 | System.out.println("parent class constructor invoked"); 365 | } 366 | } 367 | 368 | class B2 extends A{ 369 | B2(){ 370 | super(); 371 | System.out.println("child class constructor invoked"); 372 | } 373 | 374 | { 375 | System.out.println("instance initializer block is invoked"); 376 | } 377 | 378 | public static void main(String args[]){ 379 | B2 b=new B2(); 380 | } 381 | } 382 | 383 | ``` 384 | 385 | ``` 386 | Output: 387 | 388 | parent class constructor invoked 389 | instance initializer block is invoked 390 | child class constructor invoked 391 | ``` 392 | 393 | ## final 394 | 395 | The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: 396 | 397 | - variable 398 | - method 399 | - class 400 | 401 | The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword. 402 | 403 | **final variable** 404 | 405 | If you make any variable as final, you cannot change the value of final variable(It will be constant). 406 | 407 | 408 | Example 409 | 410 | ```java 411 | class Car{ 412 | final int speedLimit = 90; //final variable 413 | void run(){ 414 | speedLimit=400; 415 | } 416 | public static void main(String args[]){ 417 | Car obj=new Car(); 418 | obj.run(); 419 | } 420 | } 421 | 422 | ``` 423 | 424 | ``` 425 | Output: 426 | 427 | Compile Time Error 428 | ``` 429 | 430 | **final method** 431 | 432 | If you make any method as final, you cannot override it. 433 | 434 | ```java 435 | class Car{ 436 | final void run(){ 437 | System.out.println("running"); 438 | } 439 | } 440 | 441 | class Honda extends Car{ 442 | void run(){ 443 | System.out.println("running safely"); 444 | } 445 | 446 | public static void main(String args[]){ 447 | Honda honda= new Honda(); 448 | honda.run(); 449 | } 450 | } 451 | ``` 452 | 453 | ``` 454 | Output: 455 | 456 | Compile Time Error 457 | ``` 458 | 459 | **final class** 460 | 461 | If you make any class as final, you cannot extend it. 462 | 463 | ```java 464 | final class Car{} 465 | 466 | class Honda extends Car{ 467 | void run(){ 468 | System.out.println("running safely"); 469 | } 470 | 471 | public static void main(String args[]){ 472 | Honda honda= new Honda(); 473 | honda.run(); 474 | } 475 | } 476 | 477 | ``` 478 | 479 | ``` 480 | Output: 481 | 482 | Compile Time Error 483 | ``` 484 | 485 | ## Runtime Polymorphism 486 | 487 | Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time. 488 | 489 | In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable. 490 | 491 | Let's first understand the upcasting before Runtime Polymorphism. 492 | 493 | Upcasting 494 | If the reference variable of Parent class refers to the object of Child class, it is known as upcasting 495 | 496 | ```java 497 | class A{ 498 | 499 | } 500 | 501 | class B extends A{ 502 | 503 | } 504 | 505 | A a =new B(); //upcasting 506 | ``` 507 | 508 | Example runtime polymorphism 509 | 510 | ```java 511 | class Bike{ 512 | void run(){ 513 | System.out.println("running"); 514 | } 515 | } 516 | 517 | class Splendor extends Bike{ 518 | void run(){ 519 | System.out.println("running safely"); 520 | } 521 | 522 | public static void main(String args[]){ 523 | Bike b = new Splendor(); //upcasting 524 | b.run(); 525 | } 526 | } 527 | 528 | ``` 529 | 530 | ``` 531 | Output: 532 | 533 | running safely 534 | ``` 535 | 536 | Example 2 runtime polymorphism 537 | 538 | ```java 539 | class Shape{ 540 | void draw(){ 541 | System.out.println("drawing"); 542 | } 543 | } 544 | 545 | class Rectangle extends Shape{ 546 | void draw(){ 547 | System.out.println("drawing rectangle"); 548 | } 549 | } 550 | 551 | class Circle extends Shape{ 552 | void draw(){ 553 | System.out.println("drawing circle"); 554 | } 555 | } 556 | 557 | class Triangle extends Shape{ 558 | void draw(){ 559 | System.out.println("drawing triangle"); 560 | } 561 | } 562 | 563 | class TestPolymorphism2{ 564 | public static void main(String args[]){ 565 | Shape s; 566 | s = new Rectangle(); 567 | s.draw(); 568 | s = new Circle(); 569 | s.draw(); 570 | s = new Triangle(); 571 | s.draw(); 572 | } 573 | } 574 | 575 | ``` 576 | 577 | ``` 578 | Output: 579 | 580 | drawing rectangle 581 | drawing circle 582 | drawing triangle 583 | ``` 584 | 585 | Example polymorphism with multilevel inheritance 586 | 587 | ```java 588 | class Animal{ 589 | void eat(){ 590 | System.out.println("eating"); 591 | } 592 | } 593 | 594 | class Dog extends Animal{ 595 | void eat(){ 596 | System.out.println("eating fruits"); 597 | } 598 | } 599 | 600 | class BabyDog extends Dog{ 601 | void eat(){ 602 | System.out.println("drinking milk"); 603 | } 604 | 605 | public static void main(String args[]){ 606 | Animal a1,a2,a3; 607 | a1 = new Animal(); 608 | a2 = new Dog(); 609 | a3 = new BabyDog(); 610 | a1.eat(); 611 | a2.eat(); 612 | a3.eat(); 613 | } 614 | } 615 | ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Table of Contents 3 | 1. [Object Oriented Programming](#OOP) 4 | 2. [Principles of OOP](#principles-OOP) 5 | - [Encapsulation](#encapsulation) 6 | - [Abstraction](#abstraction) 7 | - [Inheritance](#inheritance) 8 | - [Polymorphism](#polymorphism) 9 | - [Coupling](#coupling) 10 | - [Cohesion](#cohesion) 11 | - [Association](#association) 12 | - [Aggregation](#aggregation) 13 | - [Composition](#composition) 14 | 3. [Object and Clases](#objects-classes) 15 | - [Classes](#classes) 16 | - [Objects](#objects) 17 | - [Methods](#method) 18 | - [Constructor](#constructor) 19 | - [static](#static) 20 | - [this](#this) 21 | 4. [SOLID](#solid) 22 | 23 | ## OOP - Object Oriented Programming 24 | 25 | Is a programming paradigm in which programs are organized around data, or based on the concept "objects", rather than functions and logic. 26 | 27 | Basically an object can be defined as a data (attributes or properties) and behaviors (methods) 28 | 29 | Simply put, OOP focuses on the objects that developers want to manipulate rather than the logic required to manipulate them. This approach to programming is well-suited for programs that are large, complex and actively updated or maintained. Due to the organization of an object-oriented program, this method is also conducive to collaborative development where projects can be divided into groups. Additional benefits of OOP include code reusability, scalability and efficiency. 30 | 31 | OOP was developed to increase the reusability and maintainability of source code. Transparent representation of the control flow had no priority and was meant to be handled by a compiler. With the increasing relevance of parallel hardware and multithreaded coding, developing transparent control flow becomes more important, something hard to achieve with OOP 32 | 33 | ## Principles of OOP 34 |

35 | 36 |

37 | 38 | **Object Oriented Programming is based on the following principles**: 39 | 40 | ### ```Encapsulation``` 41 | The implementation and state of each object are privately held inside a defined boundary, or class. 42 | 43 | Other objects do not have access to this class or the authority to make changes but are only able to call a list of public functions, or methods. This characteristic of data hiding provides greater program security and avoids unintended data corruption. 44 | 45 | The meaning of **Encapsulation**, is to make sure that "sensitive" data is hidden from users. To achieve this, you must: 46 | 47 | - declare class variables/attributes as ```private``` 48 | - provide public get and set methods to access and update the value of a ```private``` variable 49 | 50 | **Get and Set** 51 | 52 | You learned from the previous chapter that ```private``` variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public **get** and **set** methods. 53 | 54 | The ```get``` method returns the variable value, and the ```set``` method sets the value. 55 | 56 | Syntax for both is that they start with either ```get``` or ```set```, followed by the name of the variable, with the first letter in upper case: 57 | 58 | Example 59 | 60 | ```java 61 | public class Person { 62 | private String name; // private = restricted access 63 | 64 | // Getter 65 | public String getName() { 66 | return name; // return the value of the variable name 67 | } 68 | 69 | // Setter 70 | public void setName(String newName) { 71 | this.name = newName; // The set method takes a parameter (newName) and assigns it to the name variable 72 | } 73 | } 74 | 75 | ``` 76 | **Why Encapsulation?** 77 | 78 | - Better control of class attributes and methods 79 | - Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method) 80 | - Flexible: the programmer can change one part of the code without affecting other parts 81 | - Increased security of data 82 | 83 | [See more about Encapsulation](https://github.com/alejoalvarez/oop/blob/master/Encapsulation.md) 84 | 85 | ### ```Abstraction``` 86 | Abstract Classes and Methods 87 | 88 | Objects only reveal internal mechanisms that are relevant for the use of other objects, hiding any unnecessary implementation code. This concept helps developers make changes and additions over time more easily. 89 | 90 | Data abstraction is the process of hiding certain details and showing only essential information to the user. 91 | Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the next chapter). 92 | 93 | - **Abstract class**: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). 94 | - **Abstract method**: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from). 95 | 96 | An abstract class can have both abstract and regular methods: 97 | 98 | Example: 99 | ```java 100 | // Abstract class 101 | abstract class Animal { 102 | // Abstract method (does not have a body) 103 | public abstract void sound(); 104 | // Regular method 105 | public void sleep() { 106 | System.out.println("Zzz"); 107 | } 108 | } 109 | 110 | // Subclass (inherit from Animal) 111 | class Cat extends Animal { 112 | public void sound() { 113 | // The body of sound() is provided here 114 | System.out.println("The cat says: Miau"); 115 | } 116 | } 117 | 118 | class Main { 119 | public static void main(String[] args) { 120 | Cat myCat = new Cat(); // Create a Cat object 121 | myCat.animalSound(); 122 | myCat.sleep(); 123 | } 124 | } 125 | ``` 126 | 127 | [See more about Abstraction](https://github.com/alejoalvarez/oop/blob/master/Abstraction.md) 128 | 129 | ### ```Inheritance``` 130 | Subclass and superclass 131 | 132 | Relationships and subclasses between objects can be assigned, allowing developers to reuse a common logic while still maintaining a unique hierarchy. This property of OOP forces a more thorough data analysis, reduces development time and ensures a higher level of accuracy. 133 | 134 | Is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: 135 | 136 | - **subclass** (child) - the class that inherits from another class 137 | - **superclass** (parent) - the class being inherited from 138 | 139 | To inherit from a class, use the ```extends``` keyword. 140 | 141 | Example 142 | 143 | ```java 144 | class Vehicle { 145 | protected String brand = "Audi"; // Vehicle attribute 146 | public void honk() { // Vehicle method 147 | System.out.println("Tuut, tuut!"); 148 | } 149 | } 150 | 151 | class Car extends Vehicle { 152 | private String modelName = "Mercedez"; // Car attribute 153 | public static void main(String[] args) { 154 | 155 | // Create a myCar object 156 | Car myCar = new Car(); 157 | 158 | // Call the honk() method (from the Vehicle class) on the myCar object 159 | myCar.honk(); 160 | 161 | // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class 162 | System.out.println(myCar.brand + " " + myCar.modelName); 163 | } 164 | } 165 | ``` 166 | 167 | **Why And When To Use "Inheritance"?** 168 | 169 | - It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class. 170 | 171 | [See more about Inheritance](https://github.com/alejoalvarez/oop/blob/master/Inheritance.md) 172 | 173 | ### ```Polymorphism``` 174 | Objects are allowed to take on more than one form depending on the context. The program will determine which 175 | meaning or usage is necessary for each execution of that object, cutting down on the need to duplicate code. 176 | 177 | Refers to the ability of OOPs programming languages to differentiate between entities with the same name efficiently. 178 | 179 | Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance. 180 | 181 | Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways 182 | 183 | Example 184 | 185 | ```java 186 | class Animal { 187 | public void animalSound() { 188 | System.out.println("The animal makes a sound"); 189 | } 190 | } 191 | 192 | class Cat extends Animal { 193 | public void animalSound() { 194 | System.out.println("The cat says: Miau"); 195 | } 196 | } 197 | 198 | class Dog extends Animal { 199 | public void animalSound() { 200 | System.out.println("The dog says: Guau"); 201 | } 202 | } 203 | 204 | class Main { 205 | public static void main(String[] args) { 206 | Animal myAnimal = new Animal(); // Create a Animal object 207 | Animal myCat = new Cat(); // Create a Cat object 208 | Animal myDog = new Dog(); // Create a Dog object 209 | myAnimal.animalSound(); 210 | myCat.animalSound(); 211 | myDog.animalSound(); 212 | } 213 | } 214 | ``` 215 | 216 | **Why And When To Use "Inheritance" and "Polymorphism"?** 217 | 218 | It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class. 219 | 220 | [See more about Polymorphism](https://github.com/alejoalvarez/oop/blob/master/Polymorphism.md) 221 | 222 | ### Coupling 223 | 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. 224 | 225 | ### Cohesion 226 | 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. 227 | 228 | ### Association 229 | 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: 230 | 231 | - One to One 232 | - One to Many 233 | - Many to One, and 234 | - Many to Many 235 | 236 | 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). 237 | 238 | Association can be undirectional or bidirectional. 239 | 240 | ### Aggregation 241 | 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. 242 | 243 | ### Composition 244 | 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. 245 | 246 | ## Objects and classes 247 | Exist two main concepts in OOP: Classes and objects. 248 | 249 | ### Classes: 250 | 251 | Is a template that allow to create object, containt the definition of attributes and the procedure for the class 252 | 253 | - They are used to represent entities or concepts 254 | - Each object created from a class is called an instance of the class 255 | - Has methods (Performs a task) 256 | - It has attributes, by convention they must be private 257 | - The name must begin with a capital letter 258 | 259 | **Static class:** 260 | - No need to create instances to call them 261 | - Only static methods can be called 262 | 263 | A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: 264 | - **Modifiers**: A class can be public or has default access (Refer this for details). 265 | - **Class name**: The name should begin with a initial letter (capitalized by convention). 266 | - **Superclass(if any)**: The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. 267 | - **Interfaces(if any)**: A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. 268 | - **Body**: The class body surrounded by braces, { }. 269 | 270 | ### **Objects**: 271 | - Instances of clases 272 | - Object = instance 273 | 274 | An instance is created so you can use the methods that that class defines. 275 | 276 | It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of:
277 | - **State** : It is represented by attributes of an object. It also reflects the properties of an object. 278 | - **Behavior** : It is represented by methods of an object. It also reflects the response of an object with other objects. 279 | - **Identity** : It gives a unique name to an object and enables one object to interact with other objects. 280 | 281 | ### Method: 282 | 283 | A method is a collection of statements that perform some specific task and return result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class which is different from languages like C, C++ and Python. 284 | Methods are time savers and help us to reuse the code without retyping the code. 285 | 286 | Method Declaration: In general, method declarations has six components: 287 | 288 | - **Access Modifier**: Defines access type of the method i.e. from where it can be accessed in your application. In Java, there 4 type of the access specifiers.
289 | - **public**: accessible in all class in your application.
290 | - **protected**: accessible within the package in which it is defined and in its subclass(es)(including subclasses declared outside the package)
291 | - **private**: accessible only within the class in which it is defined.
292 | - **default** (declared/defined without using any modifier): accessible within same class and package within which its class is defined.
293 | - **The return type**: The data type of the value returned by the method or void if does not return a value. 294 | - **Method Name**: the rules for field names apply to method names as well, but the convention is a little different. 295 | - **Parameter list**: Comma separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis. If there are no parameters, you must use empty parentheses (). 296 | - **Exception list**: The exceptions you expect by the method can throw, you can specify these exception(s). 297 | - **Method body**: it is enclosed between braces. The code you need to be executed to perform your intended operations. 298 | 299 | **Ways to initialize object** 300 | 301 | There are 3 ways to initialize object in Java. 302 | 303 | - By reference variable 304 | - By method 305 | - By constructor 306 | 307 | 308 | we can create objects with 6 different methods which are: 309 | 310 | - By new keyword 311 | - By newInstance() method of Class class 312 | - By newInstance() method of constructor class 313 | - By clone() method 314 | - By deserialization 315 | - By factory method 316 | 317 | ```Java Object Creation by new keyword``` 318 | It is the most simple and common way of creating an object of a class. By using the new keyword, we can call any type of constructor of the class that is, either the parameterized constructor or non-parameterized constructor. 319 | 320 | ```java 321 | ClassName ObjectName = new ClassName(); 322 | ``` 323 | 324 | ```Java Object Creation by newInstance() method of Class class``` 325 | This is another technique to create an object of the class. We use the newInstance() method of a Class class to create an object. This newInstance() method calls the no-arg constructor of the class to create the object. 326 | 327 | ```java 328 | Class cls = Class.forName("ClassName"); 329 | ClassName objectName = (ClassName) cls.newInstance(); 330 | ``` 331 | 332 | ```Java Object Creation by newInstance() method of Constructor class``` 333 | We can also use the newInstance() method of java.lang.reflect.Constructor class to create an object. The newInstance() method of the Constructor class is similar to the newInstance() method of the Class class. 334 | 335 | ```java 336 | Constructor constructor = ClassName.class.getConstructor(); 337 | ClassName objectName = constructor.newInstance(); 338 | ``` 339 | 340 | ```Java Object Creation by clone() method``` 341 | When we call the clone() method through an object, the Java compiler automatically creates a new object of that class. JVM actually copies all content of the older object into the newly created object. 342 | 343 | To use the clone() method on an object we have to implement the Cloneable interface and override the clone() method in our class. 344 | 345 | ```java 346 | ClassName object1 = new ClassName(); 347 | ClassName object2 = (ClassName) object1.clone(); 348 | ``` 349 | 350 | ```Java Object Creation using deserialization``` 351 | When we serialize an object and then deserialize it, JVM creates a new object. To deserialize an object, we need to implement the java.io.Serializable. 352 | 353 | 354 | ```Initialization through reference:``` 355 | Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable. 356 | 357 | ```java 358 | class Student{ 359 | int id; 360 | String name; 361 | } 362 | 363 | class Main{ 364 | public static void main(String args[]){ 365 | Student student1 = new Student(); 366 | student1.id=1; 367 | student1.name="Alejo"; 368 | System.out.println(student1.id + " " + student1.name); 369 | } 370 | } 371 | ``` 372 | 373 | ```Initialization through method:``` 374 | 375 | We are creating the two objects of Student class and initializing the value to these objects by invoking the insertInformation method. Here, we are displaying the state (data) of the objects by invoking the printInformation() method. 376 | 377 | ```java 378 | class Student{ 379 | int id; 380 | String name; 381 | 382 | void insertInformation(int r, String n){ 383 | id=r; 384 | name=n; 385 | } 386 | void printInformation(){ 387 | System.out.println(id + " " + name); 388 | } 389 | } 390 | 391 | class Main{ 392 | public static void main(String args[]){ 393 | Student student1=new Student(); 394 | Student student2=new Student(); 395 | student1.insertInformation(1,"Alejo"); 396 | student2.insertInformation(2,"Alejo 1"); 397 | student1.printInformation(); 398 | student2.printInformation(); 399 | } 400 | } 401 | ``` 402 | As you can see in the above figure, object gets the memory in heap memory area. The reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory. 403 | 404 | ```Initialization through a constructor:``` 405 | 406 | ```java 407 | class Employee{ 408 | int id; 409 | String name; 410 | float salary; 411 | 412 | void insertInformation(int i, String n, float s) { 413 | id=i; 414 | name=n; 415 | salary=s; 416 | } 417 | void prprintInformationint(){ 418 | System.out.println(id + " " + name + " " + salary); 419 | } 420 | } 421 | 422 | public class TestEmployee { 423 | public static void main(String[] args) { 424 | Employee employee1=new Employee(); 425 | Employee employee2=new Employee(); 426 | 427 | employee1.insertInformation(1,"Alejo 1",45000); 428 | employee2.insertInformation(2,"Alejo 2",25000); 429 | 430 | employee1.printInformation(); 431 | employee2.printInformation(); 432 | } 433 | } 434 | ``` 435 | 436 | #### Constructor 437 | 438 | In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. 439 | 440 | It is a special type of method which is used to initialize the object. 441 | 442 | Every time an object is created using the new() keyword, at least one constructor is called. 443 | 444 | It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default. 445 | 446 | There are two types of constructors in Java: no-arg constructor, and parameterized constructor. 447 | 448 | Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any. 449 | 450 | - Create the class 451 | - Has the same name as the class 452 | - The default classes are created with an empty constructor 453 | - Occurs when an object of the type defined by the class is created 454 | - It helps us to initialize an object 455 | - Class method 456 | 457 | There are two rules defined for the constructor. 458 | 459 | - Constructor name must be the same as its class name 460 | - A Constructor must have no explicit return type 461 | - A Java constructor cannot be abstract, static, final, and synchronized 462 | 463 |

464 | 465 |

466 | 467 | ### static 468 | 469 | The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class. 470 | 471 | The static can be: 472 | 473 | - Variable (also known as a class variable) 474 | - Method (also known as a class method) 475 | - Block 476 | - Nested class 477 | 478 | **static variable** 479 | 480 | If you declare any variable as static, it is known as a static variable. 481 | 482 | - The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. 483 | - The static variable gets memory only once in the class area at the time of class loading. 484 | 485 | Advantages of static variable 486 | It makes your program memory efficient (i.e., it saves memory). 487 | 488 | ```java 489 | class Student{ 490 | int id;//instance variable 491 | String name; 492 | static String college ="TEST";//static variable 493 | 494 | Student(int i, String n){ 495 | id = i; 496 | name = n; 497 | } 498 | //method to display the values 499 | void printInformation (){ 500 | System.out.println(id + " " + name + " " + college); 501 | } 502 | } 503 | //Test class to show the values of objects 504 | public class TestStaticVariable1{ 505 | public static void main(String args[]){ 506 | Student student1 = new Student(111,"Alejo 1"); 507 | Student student2 = new Student(222,"Alejo 2"); 508 | //we can change the college of all objects by the single line of code 509 | //Student.college="TEST"; 510 | student1.printInformation(); 511 | student2.printInformation(); 512 | } 513 | } 514 | ``` 515 | 516 | **static method** 517 | 518 | If you apply static keyword with any method, it is known as static method. 519 | 520 | - A static method belongs to the class rather than the object of a class. 521 | - A static method can be invoked without the need for creating an instance of a class. 522 | - A static method can access static data member and can change the value of it. 523 | 524 | ```java 525 | class Student{ 526 | int id; 527 | String name; 528 | static String college = "TEST"; 529 | 530 | //static method to change the value of static variable 531 | static void change(){ 532 | college = "TEST2"; 533 | } 534 | 535 | 536 | Student(int i, String n){ 537 | id = r; 538 | name = n; 539 | } 540 | 541 | void printInformation(){ 542 | System.out.println(id + " " + name + " " + college); 543 | } 544 | } 545 | //Test class to create and display the values of object 546 | public class TestStaticMethod{ 547 | public static void main(String args[]){ 548 | Student.change();//calling change method 549 | 550 | Student student1 = new Student(111,"Alejo1"); 551 | Student student2 = new Student(222,"Alejo2"); 552 | 553 | s1.printInformation(); 554 | s2.printInformation(); 555 | s3.printInformation(); 556 | } 557 | } 558 | ``` 559 | There are two main restrictions for the static method. They are: 560 | 561 | - The static method can not use non static data member or call non-static method directly. 562 | - this and super cannot be used in static context. 563 | 564 | ```Why is the Java main method static?``` 565 | It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation. 566 | 567 | **static block** 568 | - Is used to initialize the static data member. 569 | - It is executed before the main method at the time of classloading. 570 | 571 | ```java 572 | class Main{ 573 | static{ 574 | System.out.println("static block is invoked"); 575 | } 576 | 577 | public static void main(String args[]){ 578 | System.out.println("Hello main"); 579 | } 580 | } 581 | ``` 582 | 583 | ```sh 584 | Output:static block is invoked 585 | Hello main 586 | ``` 587 | 588 | ```Can we execute a program without main() method?``` 589 | No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not possible to execute a Java class without the main method. 590 | 591 | ### this 592 | 593 | There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object. 594 | 595 | Here is given the 6 usage of java this keyword. 596 | 597 | - **this** can be used to refer current class instance variable. 598 | - **this** can be used to invoke current class method (implicitly) 599 | - **this()** can be used to invoke current class constructor. 600 | - **this** can be passed as an argument in the method call. 601 | - **this** can be passed as argument in the constructor call. 602 | - **this** can be used to return the current class instance from the method. 603 | 604 | 605 | **(this) refer current class instance variable.** 606 | 607 | The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity. 608 | 609 | ```java 610 | class Student{ 611 | int id; 612 | String name; 613 | float fee; 614 | 615 | Student(int id,String name,float fee){ 616 | this.id = id; 617 | this.name = name; 618 | this.fee = fee; 619 | } 620 | 621 | void printInformation(){ 622 | System.out.println(id + " " + name + " " + fee); 623 | } 624 | } 625 | 626 | class TestThis2{ 627 | public static void main(String args[]){ 628 | Student student1=new Student(111,"Alejo1",5000f); 629 | Student student2=new Student(22,"Alejo2",6000f); 630 | student1.printInformation(); 631 | student2.printInformation(); 632 | } 633 | } 634 | ``` 635 | 636 | **(this) to invoke current class method** 637 | You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example 638 | 639 | ```java 640 | class Example{ 641 | void sayHelllo1(){ 642 | System.out.println("hello 1"); 643 | } 644 | 645 | void sayHello2(){ 646 | System.out.println("hello 2"); 647 | //m();//same as this.m() 648 | this.m(); 649 | } 650 | } 651 | 652 | class TestThis4{ 653 | public static void main(String args[]){ 654 | Example example=new Example(); 655 | example.sayHelllo2(); 656 | } 657 | } 658 | 659 | //RESULT 660 | hello 2 661 | hello 1 662 | ``` 663 | **(this) to invoke current class constructor** 664 | 665 | The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining. 666 | 667 | ```java 668 | class Example{ 669 | Example(){ 670 | System.out.println("hello 1"); 671 | } 672 | 673 | Example(int x){ 674 | this(); 675 | System.out.println(x); 676 | } 677 | 678 | } 679 | class TestThis5{ 680 | public static void main(String args[]){ 681 | Example example = new Example(10); 682 | } 683 | } 684 | 685 | //RESULT 686 | hello 1 687 | 10 688 | ``` 689 | 690 | Real example 691 | ```java 692 | class Student{ 693 | int id; 694 | String name,course; 695 | float fee; 696 | 697 | Student(int id,String name,String course){ 698 | this.id=id; 699 | this.name=name; 700 | this.course=course; 701 | } 702 | 703 | Student(int id,String name,String course,float fee){ 704 | this(id,name,course);//reusing constructor 705 | this.fee=fee; 706 | } 707 | 708 | void printInformation(){ 709 | System.out.println(id + " " + name + " " + course + " " + fee); 710 | } 711 | 712 | } 713 | class TestThis7{ 714 | public static void main(String args[]){ 715 | Student student1=new Student(111,"Alejo1","java1"); 716 | Student student2=new Student(112,"sumit","java2",6000f); 717 | student1.printInformation(); 718 | student2.printInformation(); 719 | } 720 | } 721 | ``` 722 | 723 | **(this) to pass as an argument in the method** 724 | 725 | The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see the example: 726 | 727 | ```java 728 | class Example{ 729 | void printInformation(Example obj){ 730 | System.out.println("method is invoked"); 731 | } 732 | 733 | void process(){ 734 | printInformation(this); 735 | } 736 | public static void main(String args[]){ 737 | Example example1 = new Example(); 738 | example1.process(); 739 | } 740 | } 741 | 742 | //RESULT 743 | method is invoked 744 | ``` 745 | 746 | **(this) to pass as argument in the constructor call** 747 | 748 | We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see the example: 749 | 750 | ```java 751 | class B{ 752 | A4 obj; 753 | B(A4 obj){ 754 | this.obj=obj; 755 | } 756 | void display(){ 757 | System.out.println(obj.data);//using data member of A4 class 758 | } 759 | } 760 | 761 | class A4{ 762 | int data=10; 763 | A4(){ 764 | B b=new B(this); 765 | b.display(); 766 | } 767 | public static void main(String args[]){ 768 | A4 a=new A4(); 769 | } 770 | } 771 | 772 | //RESULT 773 | 10 774 | ``` 775 | 776 | **(this) keyword can be used to return current class instance** 777 | 778 | We can return this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive). Let's see the example: 779 | 780 | ```java 781 | class A{ 782 | A getA(){ 783 | return this; 784 | } 785 | 786 | void msg(){ 787 | System.out.println("Hello java"); 788 | } 789 | 790 | } 791 | class Test1{ 792 | public static void main(String args[]){ 793 | new A().getA().msg(); 794 | } 795 | } 796 | 797 | //RESULT 798 | 799 | Hello java 800 | ``` 801 | 802 | ## SOLID 803 | [View complete definition](https://github.com/alejoalvarez/SOLID) 804 | 805 |

806 | 807 |

808 | 809 | Five design principles intended to make software designs more understandable, flexible and maintainable. 810 | 811 | - **Single responsibility principle** 812 | A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class. 813 | 814 | - **Open/closed principle** 815 | "Software entities ... should be open for extension, but closed for modification." 816 | 817 | - **Liskov substitution principle** 818 | "Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program". 819 | 820 | - **Interface segregation principle** 821 | "Many client-specific interfaces are better than one general-purpose interface." 822 | 823 | - **Dependency inversion principle** 824 | One should "depend upon abstractions, [not] concretions". 825 | 826 | ## Design patterns 827 | [View complete definition](https://github.com/Alejo-Alvarezv/DesingPatterns) 828 | 829 |

830 | 831 |

832 | 833 | Is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn't a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. 834 | --------------------------------------------------------------------------------