Complete Object Oriented Programming (OOP) concept in Java


Class

A class is a collection of methods and variables. It is a blueprint that defines the data and behaviour of a type or kind. So, a class is a template for objects, and an object is an instance of a class

// Class Declaration
public class Car {
    // Instance Variables
    String brand;
    String makingYear;
    String color;
    int highSpeed;

  
    // method 1
    public String getInfo() {
        return ("Brand is: "+brand+" Making Year:"+makingYear+" Color is:"+color+" Highest speed is: "+highSpeed);
    }
    

    public static void main(String[] args) {
        Dog maltese = new Dog();
        maltese.breed="Maltese";
        maltese.size="Small";
        maltese.age=2;
        maltese.color="white";
        System.out.println(maltese.getInfo());
    }
}

 

Object

An object is a instance of Class. An object is nothing but a self-contained component which consists of methods and properties to make a particular type of data. You can also tell it as a collection of methods and variables, the structure of that object will be defined by the class.

Encapsulation

Encapsulation — private instance variable and public accessor methods. Encapsulation is the method to restricting some data access as private and retrieving those data using some public methods
.
For example, we are hiding the name and dob attributes of person class in the below code snippet.

public class Employee {
    private String name;
    private Date dob;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getDob() {
        return dob;
    }
    public void setDob(Date dob) {
        this.dob = dob;
    }
}

Inheritance

Inheritance enables the use of attributes and methods from one class to another class.

  • SubClass – The class inherits from another class.
  • SuperClass – The class being inherited from another class.

To inherit from another class you have to use “extends” keyword to inherit it.

class Vehicle {
  protected String brand = "Ford";        // Vehicle attribute
  public void honk() {                    // Vehicle method
    System.out.println("Tuut, tuut!");
  }
}

class Car extends Vehicle {
  private String modelName = "Mustang";    // Car attribute
  public static void main(String[] args) {

    // Create a myCar object
    Car myCar = new Car();

    // Call the honk() method (from the Vehicle class) on the myCar object
    myCar.honk();

    // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
    System.out.println(myCar.brand + " " + myCar.modelName);
  }
}

Final Keyword

If you do not want a class to be inherited from another class then you have to use “final” keyword before the class name.

final class Vehicle {
  ...
}
// example below is wrong will show an error
class Car extends Vehicle {
  ...
}

 

Abstraction

Abstraction is a process to hiding some details and showing only essentials information to the user. You can not call an abstract class directly to create an object. Instead you have to inherit it.

Abstract Class

Abstract class is a restricted class that can not be called directly to create an object. You have to inherit it to get it’s variables and methods.

Abstract Method

Abstract method can be called from a different class, which inherited the respective abstract class. Abstract method do not have a body inside the abstract class. The body of the abstract method will be declared from another class.

abstract class Animal {
  public abstract void animalSound();
  public void sleep() {
    System.out.println("Zzz");
  }
}

Animal myObj = new Animal(); // will generate an error

To access the abstract class you have to inherit it from another class, like the example below.

// Abstract class
abstract class Animal {
  // Abstract method (does not have a body)
  public abstract void animalSound();
  // Regular method
  public void sleep() {
    System.out.println("Zzz");
  }
}

// Subclass (inherit from Animal)
class Pig extends Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
}

class MyMainClass {
  public static void main(String[] args) {
    Pig myPig = new Pig(); // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

Interface

Java interface is another way to achieve abstraction. Interface contains some methods without bodies. Interface must be implemented by another class with “implements” keyword and the bodies of the interface methods implemented by the implemented class.

// interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void run(); // interface method (does not have a body)
}

Example of interface and implements of interface using a class

// Interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface
class Pig implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Zzz");
  }
}

class MyMainClass {
  public static void main(String[] args) {
    Pig myPig = new Pig();  // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

Important notes about interface

  • Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an “Animal” object in the MyMainClass)
  • Interface methods do not have a body – the body is provided by the “implement” class
    On implementation of an interface, you must override all of its methods
  • Interface methods are by default abstract and public
  • Interface attributes are by default public, static and final
  • An interface cannot contain a constructor (as it cannot be used to create objects)

Why And When To Use Interfaces?

  • To achieve security – hide certain details and only show the important details of an object (interface).
  • Java does not support “multiple inheritance” (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).
interface FirstInterface {
  public void myMethod(); // interface method
}

interface SecondInterface {
  public void myOtherMethod(); // interface method
}

class DemoClass implements FirstInterface, SecondInterface {
  public void myMethod() {
    System.out.println("Some text..");
  }
  public void myOtherMethod() {
    System.out.println("Some other text...");
  }
}

class MyMainClass {
  public static void main(String[] args) {
    DemoClass myObj = new DemoClass();
    myObj.myMethod();
    myObj.myOtherMethod();
  }
}

Polymorphism

It means one name many forms. It is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Static and dynamic are the two kind of polymorphism.

  • Static polymorphism is achieved using method overloading.
  • Dynamic polymorphism using method overriding.

Any Java object that can pass more than one IS-A test is considered to be polymorphic.

public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above examples −

  • A Deer IS-A Animal
  • A Deer IS-A Vegetarian
  • A Deer IS-A Deer
  • A Deer IS-A Object
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;

All the reference variables d, a, v, o refer to the same Deer object in the heap.

class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

class MyMainClass {
  public static void main(String[] args) {
    Animal myAnimal = new Animal();  // Create a Animal object
    Animal myPig = new Pig();  // Create a Pig object
    Animal myDog = new Dog();  // Create a Dog object
    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}