What do mean by polymorphism, inheritance, encapsulation?
What do mean by polymorphism, inheritance, encapsulation?
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.
Encapsulation : Encapsulation is the process of binding together the methods and data variables as a single entity. This keeps both the data and functionality code safe from the outside world. It hides the data within the class and makes it available only through the methods. Java provides different accessibility scopes (public, protected, private ,default) to hide the data from outside
Inheritance : Allows a class (subclass) to acquire the properties and behavior of another class (superclass). In Java, a class can inherit only one class(superclass) at a time but a class can have any number of subclasses. It helps to reuse, customize and enhance the existing code. So it helps to write a code accurately and reduce the development time. Java uses extends keyword to extend a class.
Polymorphism : Allows one interface to be used for a set of actions i.e. one name may refer to different functionality. Polymorphism allows an object to accept different requests of a client (it then properly interprets the request like choosing appropriate method) and responds according to the current state of the runtime system
There are two types of polymorphism :
– Compile-time polymorphism
– Runtime Polymorphism
In compile-time Polymorphism, method to be invoked is determined at the compile time. Compile time polymorphism is supported through the method overloading concept in Java.
Method overloading means having multiple methods with same name but with different signature (number, type and order of parameters).
classA{
public void fun1(int x){
System.out.println("int");
}
public void fun1(int x,int y){
System.out.println("int and int");
}
}
public class B{
public static void main(String[] args){
A obj= A();
//Here compiler decides that fun1(int)
is to be called and"int" will be printed.
obj.fun1(2);
//Here compiler decides that fun1(int,int)
is to be called and "int and int" will be printed.
obj.fun1(2,3);
}
}
In runtime polymorphism, the method to be invoked is determined at the run time. The example of run time polymorphism is method overriding. When a subclass contains a method with the same name and signature as in the super class then it is called as method overriding.
Class A{
public void fun1(int x){
System.out.println("int in A");
}
public void fun1(int x,int y){
System.out.println("int and int");
}
}
classC extends A{
public void fun1(int x){
System.out.println("int in C");
}
}
public class D{
public static void main(String[] args){
A obj;
obj= new A(); //line 1
obj.fun1(2); //line 2 (prints "int in A")
obj=new C(); //line 3
obj.fun1(2); //line 4 (prints "int in C")
}
}
Recent Comments