Basic concepts of oops in java with examples

In this tutorial we are going to see Basic concepts of oops in java with examples.

Object-Oriented Programming in Java. The principal of Oops.

Object-Oriented Programming is an acronym for Oop. Object-Oriented Programming is a programming methodology that views a program as similarly consisting of objects that interact with each other by means of actions. The world around us is made up of objects, such as people, automobiles, buildings, streets, adding machines, papers, and so forth. Each of these objects has the ability to perform certain actions, and each of these actions has some effect on some of the other objects.

Below are the main features of Object-Oriented Programming.

Encapsulation
Polymorphism
Inheritance
Abstraction

Encapsulation in Java with example.

Encapsulation is a process of binding the data(instance variable) and methods into a single unit. Now question arises how you will achieve encapsulation. Simply by making instance variable as private and providing corresponding getter and setter method(i.e JavaBeans Naming conventions).

Let’s see a simple example of encapsulation –

Employee.java.

package encapsulation;

class Employee {

 private String name;

 private int id;

 public String getName() {

   return name;
 }
 public void setName(String name) {

   this.name = name;
 }

 public int getId() {

   return id;
 }

 public void setId(int id) {

   this.id = id;

 }
}
public class Test {
    
    public static void main(String[] args) {
        
        Employee emp=new Employee();
        
        emp.setId(10);
        
        emp.setName("ram");
        
        System.out.println("Id is ==="+emp.getId());
        
        System.out.println("name is ==="+emp.getName());
    }
    
}

 

NOTE:-
Here class Test can access the data of class Employee only going through getter and setter.

The benefit of encapsulation.
The ability to make changes in your code without breaking the code of others who use your code is a big benefit of encapsulation.

Inheritance in Java with example. Benefits if inheritance.

Inheritance is one of the OOPs concepts by which one class acquires all the properties of other classes (i.e super class). Inheritance achieved by extends keyword. Inheritance is everywhere in java, even you define a single class then it follows Inheritance principle. Inheritance follows IS-A relationship. Let’s see an example –

Example 1.

package inheritance;
class Animal{

}

Here inheritance happening because Animal class is extending Object class.

Example 2.

package inheritance;
class Animal{

  static String animalName="Dog";

  public void m1(){

  System.out.println("this is m1 method of Animal");

 }
}
public class Horse extends Animal{

  public static void main(String[] args) {

  Horse h = new Horse();

  h.m1();

  System.out.println("value of animalName=="+animalName);
 }
}

 

Note –

String animalName is defied within Animal class but we can access within Horse class. Similarly, the m1() method is defined within Animal class but we are accessing within Horse class. So no need to define String animalName and method m1() in horse class, just extend the Animal class and use variables and method of Animal class. This is code reusability.

Benefit Of Inheritance.

package inheritance;
public class Employee {

public static void main(String[] args) {

    Employee e1=new Employee();

    Employee e2=new Employee();

    System.out.println(e1.equals(e2));

  }

}
  1. Here we are doing e1.equals(e2) and it works fine(i.e it will return false).As we can see equals() method is not defined within Employee class, but we are able to use it because it has already defined within Object class.
  2. Inheritance is also useful to achieve polymorphism.

Understanding Polymorphism in Java with example.

Polymorphism means more than one form. when one form (i.e methods and reference variable) behaving differently in different case its called polymorphism. There are two types of polymorphism.

  1. Compile-time polymorphism –  Compile time polymorphism is also called static binding. It’s achieved with the help of method Overloading.
  2. Run Time Polymorphism – Runtime polymorphism also called dynamic binding. It’s achieved with the help of method overriding.

Example of Compile time polymorphism.

class Hello{ 
    public void m1(){
    System.out.println("This is Method m1 without argument");
}

public void m1(String name){
    System.out.println("name is :"+name);
  }
}

public class MethodOverloading {

    public static void main(String[] args) {
    Hello h1=new Hello();
    h1.m1();
    h1.m1("ram");
  }
}

Example of Run time polymorphism.

class Animal{
    public void m1(){        
        System.out.println("This is m1 method in class Aniaml");
    }
}
class Tiger extends Animal{    
    public void m1(){        
        System.out.println("This is m1 method in class Tiger");        
    }
}
public class MethodOverriding {    
    public static void main(String[] args) {        
        Animal a=new Tiger();        
        a.m1();        
    }    
}

The output will be  – This is m1 method in class Tiger.

Dynamic Dispatch in Java with example.

Dynamic Dispatch is the process of assigning subclass objects to a superclass reference variable.

Example of dynamic dispatch.

class Animal{
    public void m1(){
        System.out.println("This is m1 method in class Aniaml");
    }
}
class Tiger extends Animal{
    public void m1(){
        System.out.println("This is m1 method in class Tiger");
    }
}
public class ExampleOfDynamicDispatch {
    public static void main(String[] args) {
        Animal a=new Tiger();
        a.m1();
    }
}

Here we can see that ” a ” is an object type of Tiger and reference type of Animal.

Abstraction in Java with Example. How to achieve abstraction in Java.

Abstraction is the process of hiding internal details. It allows users to manage and use different applications without worrying, how it has internally implemented. Let’s take a simple example. While login to any website we use username and password. Here we no need to worry what code has been written to validate username and password. Now we take a real-time scenario. Suppose we are driving a car, we never worry about how the engine is working, we just drive.

In java, we can achieve abstraction in two ways.

  1. By making classes abstract.
  2. By using the interface.

Some points related to the abstract class.

We can declare any class abstract with help of abstract keywords.
An abstract class can contain abstract as well as a non-abstract method.
The abstract class cannot be instantiated only reference can be created.
If a class is going to extend abstract class then it must override all abstract methods or if a subclass doesn’t override all the abstract methods then declare subclass as an abstract.

Some Points related to Interface.

  1. An interface is a contract for what a class can do, they say nothing about by which way class must do it.
  2. One class can implement one or more than one interface.
  3. An interface cannot implement another interface.
  4. An interface can extend one or more interfaces.
  5. The interface cannot be instantiated with a new keyword, reference can be created.
  6. we can only define constant within interface i.e by default fields define within the interface is “public static final”.
  7. An interface can have only abstract method i.e by default methods of the interface is “public abstract”.
  8. if any class is implementing interface then that class must override all the methods of the interface or if the class is not overriding all the methods of the interface then it must declare as abstract.

Difference between Abstract class and Interface in java.

Let’s see the difference between abstract and interface.

Abstract classInterface
1.An abstract class can contain both abstract as well non abstract method.1.Interface contain only abstract method.By default method of interface is public abstract.
2.Abstract class can have instance variable2.within interface we can only define constants.
3.Abstract class can have constructor.3.Interface doesn't have constructor.
4.Abstract class extended by other class with help of extend keyword.4.Interface is implemented by other class with help of implement keyword
5.Any class can extends only one abstract class.5.But in case of interface class can implement then one interface.
6.suppose there is scenario where IS-A relationship happening then go for abstract class.6.If there is no any IS-A relationship in our requirement then go for interface.
7.when we define abstract class then its our duty to provide sub class for it.7.In case of interface we can leave it for third party vendor.

Difference between method overriding and method overloading in Java.

Let’s see the difference between overriding and overloading.

Method OverloadingMethod Overriding
1.In case of method overloading argument must be change1.in case of method overriding argument must be same.
2.Return type of overloaded method can be change.2.Return type of Overridden method can not be change except covariant return type
3.It happens at compile time.3.it happens at runtime.
4.In case of method overloading exception can be change.4.In case of method overriding subclass overridden method can declare same, subclass or no exception.
5.There is no restriction for access modifier in case of overloading.5.In case of method overriding subclass overridden method must have same or less restrictive access modifier.

 

 

 

That’s all about Basic concepts of oops in java with examples.

You may like.

Exception Handling in Java with Example.

Oops concept in java docs.

Summary – We covered Basic concepts of oops in java with examples. We covered Encapsulation, Abstraction, Polymorphism and Inheritance with example.