OOPs concepts in Java

Object in Java

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or logical (tengible and intengible). The example of integible object is banking system.

An object has three characteristics:

  • state:represents data (value) of an object.
  • behavior:represents the behavior (functionality) of an object such as deposit, withdraw etc.
  • identity:Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But,it is used internally by the JVM to identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is its behavior

Object is an instance of a class.
 Class is a template or blueprint from which objects are created. So object is the instance(result) of a class.

Class in Java

A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.

data member, method, constructor, block, class and interfaceA class in java can contain:

Syntax to declare a class:


class <class_name>{  

    data member;  



Simple Example of Object and Class

In this example, we have created a Student class that have two data members id and name. We are creating the object of the Student class by new keyword and printing the objects value.

class Student1{  

 int id;//data member (also instance variable)  

 String name;//data member(also instance variable)  

 public static void main(String args[]){  

  Student1 s1=new Student1();//creating an object of Student  






What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:

By new keyword

By newInstance() method

By clone() method

By factory method etc.

1] Abstraction

 What Is Abstraction?

Abstraction in Java or Object oriented programming is a way to segregate implementation from interface and one of the five fundamentals along with Encapsulation, Inheritance, Polymorphism, Class and Object.  Abstraction in Java is achieved by  using interface and abstract class in Java. An interface or abstract class is something which is not concrete , something which is incomplete. In order to use interface or abstract class we need to extend and implement abstract method with concrete behavior. One example of Abstraction is creating interface to denote common behavior without specifying any details about how that behavior works e.g. You create an interface called Server which has start() and stop() method. This is called abstraction of Server because every server should have way to start and stop and details may differ. As I said earlier Abstraction in Java is implemented using abstract class and interface as discussed in next section. In fact what is abstraction in Java, difference between Abstraction and Encapsulation  is also a very popular core Java interview because strong OOPS skill is one of the primary requirement for Java developers.

What Is Abstract Class In Java

An abstract class is something which is incomplete and you can not create instance of abstract class. If you want to use it you need to make it complete or concrete by extending it. A class is called concrete if it does not contain any abstract method and implements all abstract method inherited from abstract class or interface it has implemented or extended. By the way Java has concept of abstract classes, abstract method but a variable can not be abstract in Java. Popular example of abstract class in Java is ActionListener which has abstract method called actionPerformed(ActionEvent ae). This method is called when an ActionEvent is fired like when you click on JButton. Its common in java to attach ActionListener with JButton by implementing abstract method actionPerformed(ActionEvent ae) using Anonymous class, as shown in below Example :


JButton  ok = new JButton("OK");

ok.addActionListener(new ActionListener(){

           public void  actionPerformed(ActionEvent ae){

               //code to handle event



An abstract method in Java doesn’t have body , its just a declaration. In order to use abstract method you need to override that method in sub class.

so when do you use abstraction ? ( most important in my view )

when you know something needs to be there but not sure how exactly it should look like. e.g. when I am creating a class called Vehicle, I know there should be methods like start() and stop() but don’t know how that start and stop method should work, because every vehicle can have different start and stop mechanism e..g some can be started by kicking or some can be by pressing buttons . Same concept apply to interface in Java as well, which we will discuss in some other post.

So implementation of those start() and stop() methods should be left to there concrete implementation e.g. Scooter , MotorBike , Car etc.

Abstraction Using Interface in Java

In Java Interface is an another way of providing abstractionInterfaces are by default abstract and only contains public, static, final constant or abstract methods. Its very common interview question is that where should we use abstract class and where should we use Java Interfaces in my view this is important to understand to design better Java application, you can go for java interface if you only know the name of methods your class should have e.g. for Server it should have start() and stop() method but we don’t know how exactly these start and stop method will work. if you know some of the behavior while designing class and that would remain common across all sub classes add that into abstract class. Interface like Runnable interface is good example of abstraction in Java which is used to abstract task executed by multiple thread. Callable is another good abstract of a task which can return value.

Abstraction : Things to Remember

1) Use abstraction if you know something needs to be in class but implementation of that varies. Abstraction is actually result of thought process and it really need good experience of both domain and Object oriented analysis and design to come up with good abstraction for your project.

2) In Java you cannot create instance of abstract class using new operator, its compiler error. Though abstract class can have constructor.

3) Abstract is a keyword in Java, which can be used with both class and method.  Abstract class can contain both abstract and concrete method. Abstract method doesn’t have body, just declaration.

4) A class automatically becomes abstract class when any of its method declared as abstract.

5) Abstract method doesn’t have method body.

6) In Java, variable cannot be made abstract , its only class or methods which would be abstract.

7) If a class extends an abstract class or interface it has to provide implementation to all its abstract method to be a concrete class. Alternatively this class can also be abstract.

Abstract class vs Interface in Java

 1) First and major difference between abstract class and interface is that, abstract class is a class while interface is a interface, means by extending abstract class you cannot extend another class because Java does not support multiple inheritance but you can implement multiple inheritance in Java.

2) Second difference between interface and abstract class in Java is that you cannot create non abstract method in interface, every method in interface is by default abstract, but you can create non abstract method in abstract class. Even a class which doesn’t contain any abstract method can be abstract by using abstract keyword.

3) Third difference between abstract class and interface in Java is that abstract class are slightly faster than interface because interface involves a search before calling any overridden method in Java. This is not a significant difference in most of cases but if you are writing a time critical application than you may not want to leave any stone unturned.

4) Fourth difference between abstract class vs interface in Java is that, interface are better suited for Type declaration and abstract class is more suited for code reuse and evolution perspective.

5) Another notable difference between interface and abstract class is that when you add a new method in existing interface it breaks all its implementation and you need to provide an implementation in all clients which is not good. By using abstract class you can provide default implementation in super class.

Create object of abstract class and interface

To create object of an abstract class just use new just like creating objects of other non-abstract classes with just one small difference, as follows:
package com.my.test;

public abstract class MyAbstractClass {
    private String name;

    public MyAbstractClass(String name)
        this.name = name;

    public String getName(){
        return this.name;


package com.my.test;

public class MyTestClass {

    public static void main(String [] args)
        MyAbstractClass ABC = new MyAbstractClass("name") {



In the same way You can create an object of interface type, just as follows:
package com.my.test;

public interface MyInterface {

    void doSome();
    public abstract void go();


package com.my.test;

public class MyTestClass {
    public static void main(String [] args)
        MyInterface myInterface = new MyInterface() {

            public void go() {
                System.out.println("Go ...");

            public void doSome() {
                System.out.println("Do ...");



2] Encapsulation 

Encapsulation is hiding the complex details and showing only the basic things to public. You can take example of a Car, under the hood there is a lot going on in the engine and parts. But, we can only see the Steering wheel, Pedals with which we can control it.
So encapsulation has two prime motives: 1) Hiding Complexity 2) Hiding the sources of change.
We control the access of classes in Java using access modifiers ( Public, protected, private, default). We encapsulate the private units in a class which can be accessed and changed with getter and setter methods in Java. This gives you controlled access, you can control who can access your data and also validation for your data.
Generally setter methods include validation for whatever data you are entering. A class employee may have a method setAge() which has a validation check for negative numbers [ Age cannot be negative ].
In this way Encapsulation works.

Encapsulation is nothing but protecting anything which is prone to change. rational behind encapsulation is that if any functionality which is well encapsulated in code i.e maintained in just one place and not scattered around code is easy to change. this can be better explained with a simple example of encapsulation in Java. we all know that constructor is used to create object in Java and constructor can accept argument. Suppose we have a class Loan has a constructor and then in various classes you have created instance of loan by using this constructor. Now requirements change and you need to include age of borrower as well while taking loan. Since this code is not well encapsulated i.e. not confined in one place you need to change everywhere you are calling this constructor i.e. for one change you need to modify several file instead of just one file which is more error prone and tedious, though it can be done with refactoring feature of advanced IDE wouldn’t it be better if you only need to make change at one place? Yes that is possible if we encapsulate Loan creation logic in one method say createLoan() and client code call this method and this method internally crate Loan object. in this case you only need to modify this method instead of all client code.

Advantage of Encapsulation in Java and OOPS

Here are few advantages of using Encapsulation while writing code in Java or any Object oriented programming language:

  1. Encapsulated Code is more flexible and easy to change with new requirements.
  2. Encapsulation in Java makes unit testing easy.
  3. Encapsulation in Java allows you to control who can access what.
  4. Encapsulation also helps to write immutable class in Java which is a good choice in multi-threading environment.
  5. Encapsulation reduce coupling of modules and increase cohesion inside a module because all piece of one thing are encapsulated in one place.
  6. Encapsulation allows you to change one part of code without affecting other part of code.


What should you encapsulate in code

Anything which can be change and more likely to change in near future is candidate of Encapsulation. This also helps to write more specific and cohesive code. Example of this is object creation code, code which can be improved in future like sorting and searching logic.

Important points above encapsulation in Java.

  1. “Whatever changes encapsulate it” is a famous design principle.
  2. Encapsulation helps in loose coupling and high cohesion of code.
  3. Encapsulation in Java is achieved using access modifierprivate,protected and public.
  4. Factory pattern , Singleton pattern in Java makes good use of Encapsulation.


Abstraction vs. Encapsulation in Java

1) First difference between Abstraction and Encapsulation is that, Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.

2) Encapsulation is also called data hiding.

3) Design principles “programming for interface than implementation” is based on abstraction and “encapsulate whatever changes” is based upon Encapsulation.

That’s all from my side on differences between Abstraction and Encapsulation in Java. Correct understanding of Encapsulation and Abstraction is must for any Java developer. Head first Object oriented Analysis and design is a great book to learn more about Abstraction, Encapsulation and other OOPS concept.


2] Inheritance 

Inheritance in Java or OOPS (Object oriented programming) is a feature which allows coding reusability.  In other words, Inheritance  self-implies inheriting or we can say acquiring something from others. Along with Abstraction, Encapsulation and Polymorphism, Inheritance forms the backbone of Object oriented programming and Java.  In Java, we use the term inheritance when one object acquires some property from other objects. In Java, inheritance is defined in terms of superclass and subclass. it is normally used when some object wants to use existing feature of some class and also want to provide some special feature, so we can say inheritance has given the advantage of reusability.

By using Inheritance between Superclass and Subclass, a IS-A Relationship is formed which means you can use any subclass object in place of the super class object e.g. if a method expects a superclass object, you can pass a subclass object to it. Inheritance in Java is also used to provide a concrete implementation of abstract class and interface in Java.
The best way to learn object-oriented programming is following both Head First Java and Head First object-oriented analysis and design, followed by Head First design pattern.These three books have taught me most of the object oriented programming concepts I know today. It’s the Head First design pattern which taught me how to write flexible code using Inheritance and Polymorphism.


How to achieve Inheritance in Java

Inheritance can be achieved in Java through two keywords:

  • extends
  • implements

Example of Inheritance in Java

Now that we know what is Inheritance in Java and some specific property of Inheritance, its time to see a real life example of Inheritance in Java. This program will help you to learn how to use Inheritance object oriented concept in your Java code.


public class  Currency {
 String description = "Unknown currency";

 public String getCurrencyDescription() {
  return description;

 public abstract double cost(double value);

public class Rupee extends Currency {
double value;
   public Rupee() {
  description = "indian rupees";
 public double cost(double v){
  return value;

In above example of Inheritance in Java, Currency is called parent class while Rupee is a child of Currency class. In object oriented programming term, Currency is super class while Rupee is a subclass. It means Rupee inherits all non-private members e.g. fields and methods. Class and Interface can only be used after extending and providing a concrete implementation of it.

Important points about Inheritance in Java

Let’s see some worth noting points about Inheritance concepts in Java programming language.

These tips are very helpful while using Inheritance in Java program.

1) As I said earlier Inheritance in Java is supported using extends and implements keyword, extends keyword is used to inherit from another Java Class and allow to reuse functionality of Parent class. While implements keyword is used to implement Interface in Java. Implementing an interface in Java  doesn’t actually meant for code reuse but provides Type hierarchy support. You can also use extends keyword when one interface extends another interface in Java.

2) If you do not want to allow Inheritance for your class than you can make it final.  final classes cannot be extended in Java and any attempt to inherit final class will result in compile time error.

2) Constructor in Java are not inherited by Sub Class. In face Constructors are chained, first statement in constructor is always a call to another constructor, either implicitly or explicitly. If you don’t call any other constructor compiler will insert super(), which calls no argument constructor of super class in Java. this keyword represent current instance of class and super keyword represent instance of super class in Java.

3) Inheritance in Java represents IS-A relationship. If you see IS-A relationship between your domain Objects and Classes than consider using Inheritance e.g. if you have a class called Programming Language than Java IS-A Programming Language and should inherit from Programming Language class.

4) Private members of Super class is not visible to Sub class even after using Inheritance in Java. Private members include any private field or method in Java.

5) Java has a special access modifier known as protected which is meant to support Inheritance in Java. Any protected member including protected method and field are only accessible in Child class or Sub class outside the package on which they are declared.

6)One of the risk of Inheritance in Java is that derived class can alter behavior of base class by overriding methods, which can compromise variants of base class e.g. if a malicious class overrides String’s equals method in Java to change the comparison logic, you may get different behavior when String reference variable points to that class. to prevent such malicious overriding, you can make your class final to disallow inheritance. But beware making a class final severely implements its client’s ability to reuse code. It make more sense from security perspective and that’s one of the reason Why String is final in Java.

7) Use @Override annotation while overriding super class’s method in subclass. This will ensure a compile time check on whether overriding method actually overrides super class method or not. Its common mistake to method instead of overriding it mostly when super class method accept Object type, common examples are equals method, compareTo method and compare() method in Java.


When to use Inheritance in Java

Many programmer says favor composition over Inheritance which is true but there are cases where Inheritance is a natural choice, Even in Java API there are many places where inheritances is used e.g. In Java collection framework most of concrete collection classes inherit from there Abstract counterpart e.g. HashSet extends AbstractSet , LinkedHashSetextends HashSet, ArrayList extends AbstractList etc. My general policy to decide whether to use Inheritance or not is to check “IS-A” relationship. For example all above example of Inheritance satisfy IS-A rule e.g. HashSet IS-A Set. Similarly if you have class called Fruit and want to create another class called Mango, its best to use inheritance and Mango should extend Fruit because Mango is a Fruit. By extending Fruit class it gets common state and behavior of Fruit object. Conversely if you find HAS-A relationship between two classes than use Composition e.g. Car HAS-A Seat, So Car class should be composed with a Seat and Seat should not extend Car here. Another general rule of Inheritance is that if you are creating a class which adds more feature into existing class, you can extend it to reuse all of its code. That’s the reason of using  Runnable interface over Thread class for creating Thread in Java.

How to use Inheritance in Java

You can use Inheritance in Java by using two keywords, extends and implements. Extends keyword is used when one Class inherit from other Class or one interface extend another interface. On the other hand implements keyword is used when which is also a form of Abstraction in Java. Interestingly, Inheritance facilitates Polymorphism in Java. By using Inheritance Sub class gets all property of Super class, except private, and can represent Super class i.e. you can store sub class instance in a Super class reference variable, which is a form of Polymorphism in Java. All flexibility which is provided by interface based design is achieved using polymorphism. Common example of this Factory where return type of Factory method should be base interface, which allows Factory method to return any implementation of base interface, which is actually created using Inheritance in Java. In next section we will an example of Inheritance, which will show How to code for inheritance.

4] Polymorphism:

Polymorphism is an Oops concept which advice use of common interface instead of concrete implementation while writing. When we program for interface our code is capable of handling any new requirement or enhancement arise in near future due to new implementation of our common interface. If we don’t use common interface and rely on concrete implementation, we always need to change and duplicate most of our code to support new implementation. It’s not only Java but other object oriented language like C++ also supports polymorphism and it comes as fundamental along with other OOPS concepts like Encapsulation , Abstraction and Inheritance.

Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word “poly” means many and “morphs” means forms. So polymorphism means many forms.

There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

How Polymorphism supported in Java

Java has excellent support of polymorphism in terms of Inheritance, method overloading and method overriding. Method overriding allows Java to invoke method based on a particular object at run-time instead of declared type while coding. To get hold of concept let’s see an example of polymorphism in Java:


public class TradingSystem{

   public String getDescription(){

      return "electronic trading system";



public class DirectMarketAccessSystem extends TradingSystem{

   public String getDescription(){

     return "direct market access system";



public class CommodityTradingSystem extends TradingSystem{

   public String getDescription(){

     return "Futures trading system";



Here we have a super class called Trading System and there two implementation DirectMarketAccessSystem andCommodityTradingSystem and here we will write code which is flexible enough to work with any future implementation of Trading System we can achieve this by using Polymorphism in Java which we will see in the further example.
Where to use Polymorphism in code

Probably this is the most important part of this Java Polymorphism tutorial and It’s good to know where you can use Polymorphism in Java while writing code. Its common practice to always replace concrete implementation with interface it’s not that easy and  comes with practice but here are some common places where I check for polymorphism:

1) Method argument:

Always use super type in method argument that will give you leverage to pass any implementation while invoking a method. For example:

public void showDescription(TradingSystem tradingSystem){



If you have used concrete implementation e.g. CommodityTradingSystem or DMATradingSystem then that code will require frequent changes whenever you add new Trading system.

2) Variable names:

Always use Super type while you are storing reference returned from any Factory method in Java, This gives you the flexibility to accommodate any new implementation from Factory. Here is an example of polymorphism while writing Java code which you can use retrieving reference from Factory:

String systemName = Configuration.getSystemName();

TradingSystem system = TradingSystemFactory.getSystem(systemName);
3) Return type of method

The return type of any method is another place where you should be using interface to take advantage of Polymorphism in Java. In fact, this is a requirement of Factory design pattern in Java to use interface as a return type for factory method.

public TradingSystem getSystem(String name){

//code to return appropriate implementation


Types of Polymorphism in Java:
There are following two type polymorphism in java.
1. Run Time Polymorphism (Method overriding)
2. Compile Time Polymorphism (Method overloading)

Overloading and Overriding in Java

1) First and major difference between Overloading and Overriding is that former occur during compile time while later occur during runtime.

2) Second difference between Overloading and Overriding is that, you can overload method in same class but you can only override method in sub class.

3) Third difference is that you can overload static method in Java but you can not override static method in Java. In fact when you declare same method in Sub Class it’s known as method hiding because it hide super class method instead of overriding it.

4) Overloaded methods are bonded using static binding and Type of reference variable is used, while Overridden method are bonded using dynamic bonding based upon actual Object.

5) Rules of Overloading and Overriding is different in Java. In order to overload a method you need to change its method signature but that is not required for overriding any method in Java.

6) Another difference between method overloading and overriding is that private and final method can not be overridden but can be overloaded in Java.

7) Overloaded method are fast as compare to Overridden method in Java.

Object Oriented Programming with Real-World Example
  • Mobile
  • Laptop