What is inheritance?
- Inheritance allows a Child class to inherit properties from its parent class. In Java this is achieved by using extends keyword. Only properties with access modifier public and protected can be accessed in child class
What is Abstraction?
- Abstraction is the quality of dealing with ideas rather than events.
- Abstraction is a process process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words user will have the information on what the object does instead of how it does it.
- In Java Abstraction is achieved using Abstract classes, and Interfaces.
- Java - Abstraction
What is Polymorphism?
- Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. In other words, polymorphism allows you define one interface and have multiple implementations.
- Java - Polymorphism
What is Encapsulation?
- Encapsulation in Java is a mechanism of wrapping variables and methods together as as single unit. In encapsulation the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class, therefore it is also known as data hiding. To achieve encapsulation in Java, we need to do the following:
- Declare the variables of a class as private.
- Provide public setter and getter methods to modify and view the variables values.
- Encapsulation in Java
- What is the advantage of Encapsulation?
- Advantages of encapsulation
- Encapsulation With Example And Benefits In Java & OOP
- The fields can be made read-only (If we don’t define setter methods in the class) or write-only (If we don’t define the getter methods in the class). For e.g. If we have a field(or variable) which doesn’t need to change at any cost then we simply define the variable as private and instead of set and get both we just need to define the get method for that variable. Since the set method is not present there is no way an outside class can modify the value of that field.
- User would not be knowing what is going on behind the scene. They would only be knowing that to update a field call set method and to read a field call get method but what these set and get methods are doing is purely hidden from them.
- It improves maintainability and flexibility and re-usability: for e.g. In the above code the implementation code of void setEmpName(String name) and String getEmpName() can be changed at any point of time. Since the implementation is purely hidden for outside classes they would still be accessing the private field empName using the same methods (setEmpName(String name) and getEmpName()). Hence the code can be maintained at any point of time without breaking the classes that uses the code. This improves the re-usability of the underlying class.