Object-Oriented Programming Concepts
OOP is a very important concept of programming languages like C++, Java, and Python. Before Object-Oriented Programming programs were treated as procedures. In Object-Oriented Programming, objects are the most important part of your program. Accessing and changing these objects to get results is the main point of Object-Oriented Programming. As the name suggests OOPs Programming language means a language that uses the OOPs concept.
The main key concepts in OOPs are:
Class
Modifiers- It defines the scope of a class. In Java Public and Default modifier is used before class.
Private and Protected modifiers can not be used with the class names
Example 1-
//Default Modifier
class Test{ ... }
Example 2-
//Public Modifier
public class Test{ ... }
Class Name- The class name should begin with capital letters (But it is not mandatory).
Example -
class DemoClass {
}
Body- In java, the class body should be surrounded with {}.
Object
Behavior- It is basically represented by the method of an object.
Entity- It is basically used to provide a unique name to an object and it enables one object to talk with other objects.
Example:
public class Example_Object_Java {
public static void main(String args[]) {
//Object Creation(Here obj is a reference variable) Example_Object_Java obj=new Example_Object_Java();
}
}
Polymorphism-
Types of Polymorphism in Java:
Inheritance-
Types of Inheritance in Java-
Encapsulation
Example:
class Encaps_Exa{
private int enc_var1;
private int enc_var2;
public void setA(int enc_var1) {
this.enc_var1=enc_var1;
}
public void setB(int enc_var2
{
this.enc_var2=enc_var2;
}
public int getA(){
return enc_var1;
}
public int getB(){
return enc_var2;
}
}
public class Example
{
public static void main(String args[])
{
Encaps_Exa obj=new Encaps_Exa();
obj.setA(10);
System.out.println(obj.getA());
obj.setB(20);
System.out.println(obj.getB());
}
}
Abstraction
In java, abstraction can be achieved in two ways-
Example-
package Java_Test;
abstract class Abs_Exm{
abstract void A1();
}
public class Abstract_Class_Imp extends Abs_Exm {
void A1()
{
System.out.println("Abstract method implemented");
}
public static void main(String[] args) {
// TODO Auto-generated method stub Abs_Exm abs=new Abstract_Class_Imp (); abs.A1();
}
}