Object oriented concepts – Java
Q: What are basic OOPS Concepts?
A: – Inheritance : When a child class acquires all the methods and properties of parent class it is called inheritance. Java supports inheritance either using classes or interfaces.
Encapsulation: In above class, we have declared id as private and defined two methods that will act as mutator and accessors for this id propert. Thus we are encapsulateing objects property and methods with in an object, keeping it safe from outside world.
Polymorphism: In below scenario, we have added 2 declaration of a function add() to child class, one is for adding integers and another is to add float values. This kind of behavior when same name is used to perform different tasks as per the parameters passed to it is called polymorphism.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
class Parent { private int id; public Parent() { aMethod(); } public void aMethod() { System.out.println("I am in Parent"); } public int getId() { return this.id; } public void setId(int id) { this.id = id; } } class Child extends Parent { public Child() { bMethod(); } public void bMethod() { System.out.println("I am in Child"); } public void add(int a, int b) { } public void add(float a, float b) { } } |
In java polymorphism is achieved by function overloading. It is also called Compile time Polymorphism. Compile decides at compile time that which version of function is called depending up on the parameters passed.
function overriding is also type of polymorphism, some times it is called Run time polymorphism, because the methods version is decided depending on the reference type of object at run time.
Important Notes:
- return type is not part of method signature, so mere change of return types will not qualify a method to be polymorphic.
- if only parameter names are changed then that is not polymorphism.
1 2 3 4 5 6 7 8 |
public void aMethod(int a, long b) { System.out.println("int a, long b"); } public void aMethod(long a, int b) { System.out.println("long a, int b"); } |
For above methods to be polymorphic you need to use them as –
1 2 3 4 |
someobject.aMethod(1,2L); someobject.aMethod(1L,2); //someobject.aMethod(1,2); //compile time error //someobject.aMethod(2,1); //compile time error |