OOPs concepts in java with examples

You are currently viewing OOPs concepts in java with examples
Java OOPs concepts

OOPs concepts in java with examples of Abstraction, Encapsulation, Inheritance, Polymorphism, Object and Classes are illustrated here. OOPs concepts are the building blocks to write computer programs consisting of data and methods. The other related concepts Abstract method, Abstract Class, Coupling, Cohesion etc, which are also important to be learned in order to understand OOPs concepts in depth. In this article all concepts are explained with object oriented programming examples. So let’s see what OOPs concepts actually are.

Object-oriented programming System(OOPs) is a programming paradigm entirely based on the concepts of object and class. A class is a data type with named attributes and methods, whereas an object is an instance of a class data type, present in memory. An object can contain logic and data. The logic is present in the form of code grouped and categorized, known as methods or procedures. The data is the value of the attributes/properties present inside the object.

1. What is a class in Java

A class is a skeleton which consists of variables (known as member attributes) and processing logic (in the form of methods or functions). A class only defines the member attributes and class methods, which means neither member attributes hold any value nor methods include any processing logic. A class member attribute provides the name and datatype for a value which can be stored in the state of the object. A class method defines the template for input parameters, output parameters and method name, which can be called from object level. 

A class is a template or blueprint of program code for creating objects/instances, implementation of behavior and providing initial values for its attributes. 

In Java, a class can be  created using the keyword class and every class has 1 or more constructors. Constructors are the basically special type of methods in the class, which are used to initialize the class to create an object.

Example of class in Java

Here is the first example of OOPs concepts in java, we are creating  a class with the name Person. The Person class has 2 member attributes. First attribute is name which has datatype as String and second attribute is age which has datatype as int.

This class contains 1 parameterized constructor which takes 2 inputs and 1 class method named as introduction which doesn’t have any input or output parameters. This method prints the state of the object.

public class Person{
   private String name;   
   private int age;
   public Person(String name, int age){
      this.name = name;
      this.age = age;
   public String introduction(){
      System.out.println(“Name:”+ name +”, Age:”+ age);

2. What is an Object in Java

An object is an implementation of a class, an object has a defined state and defined behaviour. The state of an object is defined by the values present inside the member fields. The behaviour of an object is defined by the programming logic added within the methods. All these member attributes and methods are defined & identified by the underlying class of object.

Example of Object in Java

In this example, we are creating 2 objects of class Person. The first object is named as person1 and holds the state of the object with 2 values, name attribute has value as Robert and age attribute has value as 30. The second object is named as person2 and holds the state of the object with 2 values, name attribute has value as Sam and age attribute has value as 26. The class method “introduction” is being called on both objects person1 and person2.

public class PersonExample{
   public static void main(String args[]){
      Person person1 = new Person(“Robert”, 30);
      Person person2 = new Person(“Sam”, 26);

3. Abstraction in Java with Example

Abstraction is a process of hiding the internal details and giving the essential details only. The non-essential properties and implementation logic is completely hidden from the outer world.

In Java, abstraction is achieved by usage of interfaces and abstract classes. In simple words, abstraction is done either by using abstract classes or abstract methods. OOPs concepts in java with examples of abstraction is the first step towards seeing the big picture.

Abstract class & abstract methods:

  1. An abstract class is a class which is defined with the keyword ‘abstract
  2. A method which doesn’t have any implementation and has only a skeleton is known as an abstract method.
  3. An abstract class has at least 1 abstract method, it’s not necessary to have all methods as abstract methods.
  4. The subcall or implementation class will either implement the abstract method or will be defined as abstract class.
  5. A class which contains one or more abstract methods must be defined with the keyword abstract.
  6. Objects of an abstract class cannot be created. An abstract class can nott be instantiated an instance with the new operator .
  7. An abstract class always has a default constructor, it can have parameterized constructors too.

Abstraction Example in Java

In the following example, we have one abstract class “shape” which has one abstract method “draw”. There are 2 subclasses “Circle” and “Triangle” which extends the class “Shape” and provides the custom implementation of abstract method  “draw”.

// Abstract class
abstract class Shape {
  // Abstract method (does not have a body)
  public abstract void draw();
// Subclass
class Triangle extends Shape {
  public void draw() {
    System.out.println("Draw a triangle");

// Subclass
class Circle extends Shape {
  public void draw() {
    System.out.println("Draw a Circle");
class AbstractionTest {
  public static void main(String[] args) {
    Shape circle = new Circle(); 
    Shape triangle = new Triangle(); 

Benefits of Abstraction

  1. Abstraction is helpful in terms of security of data and avoiding accidental change in state of undesired attributes.
  2. Abstraction helps to maintain low complexity for software’s design and implementation process.
  3. Multiple related classes can be grouped together as siblings by using abstract classes.

4. Encapsulation in Java with Example

Encapsulation in Java is the phenomenon of wrapping the attributes (data) and implementation logic (methods) acting on the data together as a single entity. The attributes of the class are hidden from other classes and access is granted through the methods from the class, this is a data hiding technique.

In Java, encapsulation can be achieved by following way:

  • All class variables should be declared as private.
  • Create setters and getters for all variables to get and set the values.

Encapsulation Example in Java

An example of encapsulation can be discussed using the example of java.util.Hashtable. There are 2 methods “put” and “get”, which can add new values and retrieve existing values. So here, the user knows how he can add or retrieve the values but the actual implementation of adding, searching or getting the value from Hashmap is hidden. Without bothering about the inner implementation, one can use a class.

Benefits of Encapsulation

  1. Encapsulation provides a secure way to access the variables from unwanted access or modification.
  2. Encapsulation enables users to use the object without knowing the internal details of implementation.
  3. It helps to simplify the maintenance of the application.

5. Inheritance in Java with Example

Inheritance is a mechanism of inheriting a class into another class, retaining similar implementation and properties. Inheritance helps in reusability of code and overriding only that logic, which is unique to new class. A class which inherits another class is known as a subclass class. A class which is being inherited is known as superclass.

Inheritance Syntax in Java

The keyword “extends” is used to inherit a class into another class. A subclass name is followed by the keyword “extends” and then followed by the name of superclass.

class Child extends Parent{

Inheritance Example in Java

In this example, we have a class Circle which has a predefined radius of 20 and a method to print the draw statement. A subclass ColoredCircle here extends the superclass Circle. The subclass ColoredCircle uses the existing method and radius property of parent class, additionally, ColoredCircle has a new property name “color”;

class Circle {
  int radius  = 20;
  public void draw() {
    System.out.println("Draw a Circle");
class ColoredCircle extends Circle {
  String color = “green”;

Types of Inheritance

  1. Single Inheritance: Single Inheritance means where a class simply extends another class.
  2. Multilevel inheritance: Multilevel inheritance means the superclass is itself a subclass of another class. For example class C extends class B and class B extends class A.
  3. Hierarchical inheritance: Hierarchical inheritance means when a class is inherited by more than 1 class. For example Class B extends class A and class C also extends class A.
  4. Multiple Inheritance: Multiple inheritance means when a subclass has more than 1 superclass. In Java, multiple inheritance is not supported.

Benefits of Inheritance

  1. Reusability – The public methods of base class can be used directly without rewriting.
  2. Extensibility – As per business logic of the derived class, extending the base class logic.
  3. Data hiding – Superclass can decide to keep some properties private so that it cannot be modified by the subclass.
  4. Overriding – With inheritance, methods of base class can be overridden in subclass if required.

6. Polymorphism in Java with example

Polymorphism in Java is the ability of an object to perform a single action in different ways or to take on many forms. When a superclass reference is used to refer to a subclass object, its polymorphism in Java.

In Java, an object is always accessible by reference variable. A reference variable once declared, its type cannot be changed and it can refer to a single type. If a reference variable is not declared final then  it can be reassigned to other objects of the same type.

A reference variable can reference an object of its initially declared type or any subtype of declared type. A reference variable is declared as an interface type or class type.

Types of Polymorphism

There are 2 types of Polymorphism in java. These are called Static Polymorphism/ Compile time Polymorphism and Dynamic Polymorphism/Runtime Polymorphism.

1. Static Polymorphism/Compile time Polymorphism

Static polymorphism in Java is achieved by using the method overloading. Method overloading represents that there are multiple methods present in a class, all have the same name but different implementation or arguments.

During Compilation, JVM knows very well which method will be invoked by using the method signature. This form of polymorphism is known as static binding or compile time polymorphism or static polymorphism.

Following is a static polymorphism example in Java. Here a method with the name “sum” is overloaded with 3 different forms. Based upon the type and number of arguments, JVM knows at compile time that which method needs to be called at what place.

class StaticPolymorphismExample{
    public int sum(int a, int b){  //Form 1 of sum method
        return a+b;
    public int sum(int a, int b, int c){  //Form 2 of sum method
        return a+b+c;
    public int sum(double a, int b){  //Form 3 of sum method
        return (int)a + b;
class Main{
    public static void main(String[] args){
    StaticPolymorphismExample object1=new StaticPolymorphismExample();
    System.out.println(object1.sum(5, 6));      //Form 1 called
    System.out.println(object1.sum(4, 5, 6));    //Form 2 called
    System.out.println(object1.sum(5.2, 7));    //Form 4 called

2. Dynamic Polymorphism/Runtime Polymorphism

Dynamic polymorphism in Java is achieved by using the method overriding. Method overriding means that superclass has a defined method which is again defined in subclass. The reference variable’s type at run time decides that method from superclass or subclass will be invoked. This form of polymorphism is known as dynamic polymorphism or runtime polymorphism.

Following is a dynamic polymorphism example in Java. Here a method with the name “fly” is declared in superclass “Bird” and again overridden in subclass “Parrot”. Based upon the reference type of object, JVM decides at runtime which method needs to be called at what place.

class Bird{
    public void fly(){
        System.out.println("Bird can fly.");
class Parrot extends Bird{
    public void fly(){
        System.out.println("Parrot can fly and talk.");
public class Main{
    public static void main(String[] args){
	    Bird bird=new Parrot();
	    bird.fly();    // prints Parrot can fly and talk.
	    bird = new Bird();
	    bird.fly();    // prints Bird can fly.


Benefits of Polymorphism

  1. Polymorphism helps in code reusability i.e., a class written a long time back and tested, can be reused whenever required, which saved a lot of time.
  2. Single variables can be used to refer to multiple types.
  3. Same standard method name can be used to operate differently on different type of arguments

6. Coupling

Coupling refers to the degree of direct knowledge that one object has of another object. Coupling is also known as collaboration, where one object depends on another object to do some work. In simple words, an object’s interaction with another object is coupling. The way one object gets another object is categorized into 2 types tight coupling and loose coupling.

Tight coupling

Tight coupling is a situation when an object of a class is instantiated and internally that object instantiates some other class’s object for its internal usage. The internal object can’t be changed from outer world and used by main object only internally.

class ArticleService {
   ArticleRepository articleRepository;
   public ArticleService() {
      //tightly coupled
      articleRepository = new ArticleRepository();

   public void saveArticle(Article A) {

Loose coupling

Loose coupling is a situation when an object of a class requires some other object for some operations and the required object is passed from the external world to that object. In this case, the main object don’t have much control. The passed object’s reference can be changed at any time.

class ArticleService {
   ArticleRepository articleRepository;
   public ArticleService(ArticleRepository articleRepository) {
      //loosely coupled
      this.articleRepository = articleRepository;

   public void saveArticle(Article A) {

8. Cohesion

Cohesion is a measure of design of a single class. A well-defined purpose and well focused class has meaningfully and strongly related methods, this is the main requirement for Object Oriented principle cohesion. Greater the degree of cohesion, more easy the maintainability of code. Cohesion is categorized into 2 types: low cohesion and high cohesion. 

Low Cohesion

When a class is designed to do many different types of tasks rather than a single focused specialized task, then this class is a low cohesive class. A low cohesive class is a badly designed class, as it impacts maintainability and readability of code.

Example of low cohesion in Java is shown below, here in a single class we are trying to have processing logic, printing, saving and sending emails etc. 

class ArticleService(){
	public void processArticle();
	public void print();
	public void save();
	public void email();
	public void getDatabaseConnection();
	public void getCurrentUser();

High Cohesion

When a class is designed to do a specific specialized task, then this class is a high cohesive class. A high cohesive class is easy to maintain and update.

Example of high cohesion in Java is shown below, here in a single class we are trying to do only 1 specific task to email.

class EmailService(){
	public String getEmailBody();
	public String sendEmail();


This was the introduction to oops concepts in java with examples. If you want to install Java, then you may refer to detailed steps here for Java installation guide.

This Post Has One Comment

Comments are closed.