OOPS in Java : Brief about Object Oriented Programming Concepts
In a hurry to grab all things before an interview !!? Here, I’m sharing some brief information about OOPS in Java with code examples.
INHERITANCE -
Inheritance means the parent-child relationship between the classes in which a child has the ability to access it’s parent’s methods.
NOTE — In languages like Java, JavaScript, multiple inheritance cannot be possible.
OBJECT DECLARATIONS IN INHERITANCE -
ClassA Object = new ClassA(); //class A is the parent class of class B.
Result — Object can access the variables and methods of classA only because parent cannot access methods and variables of its child class.
ClassB Object = new ClassB(); //class A is the parent class of class B.
Result — This object will first find the variables and methods to be accessed first, if it does not find the required variables and methods inside itself then it will go to the parent class and find there.
ClassA Object = new ClassB(); //class A is the parent class of class B.
Result — This object can access only classA variables but in case of methods, it will first find the called method inside the classB, if it does not find there then it will find in the parent class.
ClassB Object = new ClassA(); //class A is the parent class of class B.
Result — This statement gives an error because child class cannot be used as a reference to its parent class object.
POLYMORPHISM -
Polymorphism allows us to perform a single action in different ways. There are two types of polymorphism —
- Static Polymorphism/Function Overloading/Static Binding
- Dynamic Polymorphism/Function Overriding/Dynamic Binding
Method Overloading -
Method overloading means you can declare multiple methods with the same name in same class with different number of arguments.
Example -
Method Overriding -
Method overriding means you can modify the parent class methods inside the child class according to the requirements of the child class.
Example -
ENCAPSULATION —
Encapsulation means a block around the code which ensures the code’s security and accessibility. It provides full control over the variables and methods inside a class.
There are four types of access modifiers in Java OOP — You can understand the difference among these modifiers in the given diagram.
ABSTRACTION —
Abstraction class contains only method declaration not implementation. An abstract class tells us what the method does instead of how it does it. This concept is used to hide implementation of methods from the users.
- Abstract methods can only be declared in an abstract class or interface.
- Methods without abstract keyword inside the abstract class can have body.
- You can implement the abstract class methods in another class by inheriting the class and overriding their methods.
If you want a full detail blog on these concepts, let me know in the comments. Give some applause if you find it helpful.