BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

OOPs Concepts in Java With Examples

By Chaitanya Singh | Filed Under: java

In this guide, you will learn the OOPs Concepts in Java. Object-oriented programming System(OOPs) is a programming concept that is based on “objects”. The primary purpose of object-oriented programming is to increase the readability, flexibility and maintainability of programs.

Object oriented programming brings data and its behaviour together in a single entity called objects. It makes the programming easier to understand. We will cover all the features of OOPs such as inheritance, polymorphism, abstraction, encapsulation in detail so that you won’t face any difficultly understanding OOPs in Java.

Popular programming languages that supports object oriented programming are: Java, C++, Python, C#, Perl, JavaScript, Ruby, Smalltalk etc.

What is OOPs Concepts in Java

OOPs concepts includes following Object oriented programming concepts:

  • Object
  • Class
  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism
OOPs features, Object-oriented-programming-features

1. Object

An object can be represented as an entity that has state and behaviour. For example: A car is an object that has states such as color, model, price and behaviour such as speed, start, gear change, stop etc.

OOPs Concepts in Java - Object Class

Let’s understand the difference between state and behaviour. The state of an object is a data item that can be represented in value such as price of car, color, consider them as variables in programming. The behaviour is like a method of the class, it is a group of actions that together can perform a task. For example, gear change is a behaviour as it involves multiple subtasks such as speed control, clutch, gear handle movement.
Let’s take few more examples of Objects:

Examples of states and behaviours
Example 1:
Class: House
State: address, color, area
Behaviour: Open door, close door

Let’s see how can we write these state and behaviours in a java program. States can be represented as instance variables and behaviours as methods of the class.

class House {
   String address;
   String color;
   double area;
   void openDoor() {
      //Write code here
   }
   void closeDoor() {
      //Write code here
   }
 ...
 ...
}

Example 2:
Class: Car
State: color, brand, weight, model
Behaviour: Break,  Accelerate,  Slow Down,  Gear change.

Note: As we have seen in the above example, the states and behaviours of an object can be represented by variables and methods in the class.

2. Class

A class can be considered as a blueprint which you can use to create as many objects as you like. For example, here we have a class Website that has two data members. This is just a blueprint, it does not represent any website, however using this we can create Website objects that represents the websites. We have created two objects, while creating objects we provided separate properties to the objects using constructor.

public class Website {
   //fields (or instance variable)
   String webName;
   int webAge;

   // constructor
   Website(String name, int age){
      this.webName = name;
      this.webAge = age;
   }
   public static void main(String args[]){
      //Creating objects
      Website obj1 = new Website("beginnersbook", 11);
      Website obj2 = new Website("google", 28);

     //Accessing object data through reference
     System.out.println(obj1.webName+" "+obj1.webAge);
     System.out.println(obj2.webName+" "+obj2.webAge);
   }
}

Output:

beginnersbook 11
google 28

3. Abstraction

Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user. For example, when you login to your bank account online, you enter your user_id and password and press login, what happens when you press login, how the input data sent to server, how it gets verified is all abstracted away from the you. Read more about it here: Abstraction in Java.

Abstract Class Example:

Here we have an abstract class Animal that has an abstract method animalSound(), since the animal sound differs from one animal to another, there is no point in giving the implementation to this method as every child class must override this method to give its own implementation details. That’s why we made it abstract.

Now each animal must have a sound, by making this method abstract we made it compulsory to the child class to give implementation details to this method. This way we ensures that every animal has a sound.

//abstract class
abstract class Animal{
   //abstract method
   public abstract void animalSound();
}
public class Dog extends Animal{

   public void animalSound(){
	System.out.println("Woof");
   }
   public static void main(String args[]){
	Animal obj = new Dog();
	obj.animalSound();
   }
}

Output:

Woof

4. Encapsulation

Encapsulation simply means binding object state(fields) and behaviour(methods) together. If you are creating class, you are doing encapsulation.

Example

1) Make the instance variables private so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the fields.

class EmployeeCount
{
   private int numOfEmployees = 0;
   public void setNoOfEmployees (int count)
   {
       numOfEmployees = count;
   }
   public double getNoOfEmployees () 
   {
       return numOfEmployees;
   }
}
public class EncapsulationExample
{
   public static void main(String args[])
   {
      EmployeeCount obj = new EmployeeCount ();
      obj.setNoOfEmployees(5613);
      System.out.println("No Of Employees: "+(int)obj.getNoOfEmployees());
    }
}

Output:

No Of Employees: 5613

The class EncapsulationExample that is using the Object of class EmployeeCount will not able to get the NoOfEmployees directly. It has to use the setter and getter methods of the same class to set and get the value.

What is the benefit of using encapsulation in java programming?
Well, at some point of time, if you want to change the implementation details of the class EmployeeCount, you can freely do so without affecting the classes that are using it.

5. Inheritance

The process by which one class acquires the properties and functionalities of another class is called inheritance. Inheritance provides the idea of reusability of code and each sub class defines only those features that are unique to it, rest of the features can be inherited from the parent class.

  1. Inheritance is a process of defining a new class based on an existing class by extending its common data members and methods.
  2. Inheritance allows us to reuse of code, it improves reusability in your java application.
  3. The parent class is called the base class or super class. The child class that extends the base class is called the derived class or sub class or child class.

Note: The biggest advantage of Inheritance is that the code in base class need not be rewritten in the child class.
The variables and methods of the base class can be used in the child class as well.

Syntax: Inheritance in Java

To inherit a class we use extends keyword. Here class A is child class and class B is parent class.

class A extends B
{
}

Generalization and Specialization:
In order to implement the concept of inheritance in an OOPs, one has to first identify the similarities among different classes so as to come up with the base class.

This process of identifying the similarities among different classes is called Generalization. Generalization is the process of extracting shared characteristics from two or more classes, and combining them into a generalized superclass. Shared characteristics can be attributes or methods.

In contrast to generalization, specialization means creating new subclasses from an existing class. If it turns out that certain attributes or methods only apply to some of the objects of the class, a subclass can be created.

Inheritance Example

In this example, we have a parent class Teacher and a child class MathTeacher. In the MathTeacher class we need not to write the same code which is already present in the present class. Here we have college name, designation and does() method that is common for all the teachers, thus MathTeacher class does not need to write this code, the common data members and methods can inherited from the Teacher class.

class Teacher {
   String designation = "Teacher";
   String college = "Beginnersbook";
   void does(){
	System.out.println("Teaching");
   }
}
public class MathTeacher extends Teacher{
   String mainSubject = "Maths";
   public static void main(String args[]){
      MathTeacher obj = new MathTeacher();
      System.out.println(obj.college);
      System.out.println(obj.designation);
      System.out.println(obj.mainSubject);
      obj.does();
   }
}

Output:

Beginnersbook
Teacher
Maths
Teaching

Note: Multi-level inheritance is allowed in Java but multiple inheritance is not allowed as shown in the following diagram.

multilevel and multiple inheritance diagram representation, Object oriented programming concepts

Types of Inheritance:
Single Inheritance: refers to a child and parent class relationship where a class extends the another class.

Multilevel inheritance: refers to a child and parent class relationship where a class extends the child class. For example class A extends class B and class B extends class C.

Hierarchical inheritance: refers to a child and parent class relationship where more than one classes extends the same class. For example, class B extends class A and class C extends class A.

Multiple Inheritance: refers to the concept of one class extending more than one classes, which means a child class has two parent classes. Java doesn’t support multiple inheritance, read more about it here.

Most of the new OO languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple Inheritance is supported in C++.

6. Polymorphism

Polymorphism is a object oriented programming feature that allows us to perform a single action in different ways. For example, let’s say we have a class Animal that has a method animalSound(), here we cannot give implementation to this method as we do not know which Animal class would extend Animal class. So, we make this method abstract like this:

public abstract class Animal{
   ...
   public abstract void animalSound();
}

Now suppose we have two Animal classes Dog and Lion that extends Animal class. We can provide the implementation detail there.

public class Lion extends Animal{
...
    @Override
    public void animalSound(){
        System.out.println("Roar");
    }
}

and

public class Dog extends Animal{
...
    @Override
    public void animalSound(){
        System.out.println("Woof");
    }
}

As you can see that although we had the common action for all subclasses animalSound() but there were different ways to do the same action. This is a perfect example of polymorphism (feature that allows us to perform a single action in different ways).

Types of Polymorphism
1) Static Polymorphism
2) Dynamic Polymorphism

Static Polymorphism:

Polymorphism that is resolved during compiler time is known as static polymorphism. Method overloading can be considered as static polymorphism example.

Method Overloading: This allows us to have more than one methods with same name in a class that differs in signature.

class DisplayOverloading
{
    public void disp(char c)
    {
         System.out.println(c);
    }
    public void disp(char c, int num)  
    {
         System.out.println(c + " "+num);
    }
}
public class ExampleOverloading
{
   public static void main(String args[])
   {
       DisplayOverloading obj = new DisplayOverloading();
       obj.disp('a');
       obj.disp('a',10);
   }
}

Output:

a
a 10

When I say method signature I am not talking about return type of the method, for example if two methods have same name, same parameters and have different return type, then this is not a valid method overloading example. This will throw compilation error.

Dynamic Polymorphism

It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in which a call to an overridden method is resolved at runtime rather, thats why it is called runtime polymorphism.

Example

class Animal{
   public void animalSound(){
	System.out.println("Default Sound");
   }
}
public class Dog extends Animal{

   public void animalSound(){
	System.out.println("Woof");
   }
   public static void main(String args[]){
	Animal obj = new Dog();
	obj.animalSound();
   }
}

Output:

Woof

Since both the classes, child class and parent class have the same method animalSound. Which of the method will be called is determined at runtime by JVM.

Few more overriding examples:

Animal obj = new Animal();
obj.animalSound();
// This would call the Animal class method

Dog obj = new Dog();
obj.animalSound();
// This would call the Dog class method

Animal obj = new Dog();
obj.animalSound();
// This would call the Dog class method

Frequently asked questions on OOPs concepts in Java

1. What are four basic OOPs concepts in Java?

The four basic features of Object Oriented programming are abstraction, encapsulation, inheritance and polymorphism.

2. Explain oops concepts in Java with realtime examples

Encapsulation real time example: A person class has a variable Aadhar number which is declared private so the other class extending this class won’t have access to the Aadhar number. This is the perfect example of encapsulation where hiding sensitive information from the outside classes.

Abstraction real time example:
When you are performing online transaction on the bank website, the page shows you relevant information such as bank account number, amount entered etc. However it hides the unnecessary details from the user such as how the bank is handling the transaction at the backend.

Inheritance real time example:
Consider a class Human, and subclasses such as Male, Female etc. Now these classes are extending properties such as skin color, hair, eyes, teeth etc from Human class and behaviours such as walking, talking, eating etc.

Polymorphism real time example:
Let’s say an Animal class has animalSound() method. The class extending this Animal class overrides this method. For example: Lion class overrides this method with “Roar” sound, while Cat class overrides this method “Meow” sound.

3. What are the OOPS concepts in Java with examples?

The following are the some of the popular OOPs concepts in Java with examples:
1. Class – Blueprint used to create object.
2. Object – An entity that represents state and behaviour.
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
7. Association – Association establishes relationship between two separate classes through their objects. The relationship can be one to one, One to many, many to one and many to many. example here
8. Aggression – It represents HAS-A relationship between two classes. It is strictly a one way association. example here
9. Composition

4. What are the advantages of OOPs?

Object oriented programming has following advantages:

Code Re-usability

A class, variables and methods can be reused in other classes.

Easier Code maintenance

It is easier to do maintenance as the code is easier to troubleshoot.

Security

Encapsulation and abstraction features of OOPs concepts allows better security and prevents potential data leaks.

Flexible

It is easier to add more code to existing programs and remove or update existing code.

5. Define access Specifiers in OOPs Concepts in Java

Well, you must have seen public, private keyword in the examples I have shared above. They are called access specifiers as they decide the scope of a data member, method or class.

There are four types of access specifiers in java:
public: Accessible to all. Other objects can also access this member variable or function.

private: Not accessible by other objects. Private members can be accessed only by the methods in the same class. Object accessible only in class in which they are declared.

protected: The scope of a protected variable is within the class which declares it and in the class which inherits from the class (Scope is class and subclass).

Default: Scope is Package Level. We do not need to explicitly mention default as when we do not mention any access specifier it is considered as default.

6. What is Message passing in OOPs concepts?

OOPs concepts in Java, Message passing

A single object by itself may not be very useful. An application contains many objects. One object interacts with another object by invoking methods on that object. It is also referred to as Method Invocation. See the diagram below.

What will we learn in the next tutorials on OOPs Concepts

We have covered almost all the topics related to OOPs concepts in Java, but the topics that we have learned in this guide are covered in detail in separate tutorials with the help of examples.

How can you read the next tutorials in a sequential manner? There are couple of ways to do it:

1) Tutorial links are provided in the left sidebar, go though them in the given sequence.

2) Go to the main java tutorial page that has all the links to the tutorials in the sequential manner.

❮ PreviousNext ❯

Comments

  1. sasikumar says

    July 23, 2013 at 12:31 PM

    your article so good and simple to understand.Thanks for post these valuable article.

    Reply
  2. Savita Shinde says

    April 10, 2014 at 8:06 AM

    One of the best website for beginners..

    Reply
  3. utkal samal says

    April 22, 2014 at 4:37 PM

    The Article which is posted , it is so so so helpful to me as well as who are visiting the site,
    Thanks a lot to you.

    I got to clear about lot of concept in java from this Article.

    Reply
  4. venkat shiva says

    June 18, 2014 at 11:40 AM

    simply understand this site helpful of b tech students……………….thnq……i love this site

    Reply
  5. sandhu says

    July 6, 2014 at 3:58 PM

    best concepts………………

    Reply
  6. savi says

    August 6, 2014 at 6:45 AM

    good

    Reply
  7. murugan says

    December 15, 2014 at 4:23 AM

    your site so good and simple to understand.Thanks for post.

    Reply
  8. Raju says

    December 15, 2014 at 7:26 AM

    Your explanation is very good.
    In java there no access specifiers. We have only Access Modifiers.In C++ we have both specifiers and modifiers.
    While creating class in Eclipse or in any IDE check it

    Reply
  9. Manoj says

    December 19, 2014 at 7:56 PM

    Really can’t appreciate enough the effort you put to explain the concepts and examples so clearly. Hats off..Great job indeed!!

    Reply
  10. shankar says

    December 30, 2014 at 4:04 PM

    i left all my books by seeing this website too good for beginners
    way of examples and explanations were too good that everyone can understand it
    mean while fix bugs at index sheet maintenance

    Reply
  11. arun kumar says

    March 16, 2015 at 2:31 PM

    i really appreciate the people who made this website…i learnt a lot from this website..and came to know that this is very helpful for me to clear the doubts in java..!!
    thank you..!!

    Reply
  12. Rojalin Bhutia says

    June 17, 2015 at 7:06 PM

    Its a GOOD website for Interview preparation.i can say it is a BEST website for freshers.Thank you..

    Reply
  13. devon says

    June 22, 2015 at 9:50 AM

    Good for beginners !!

    Reply
  14. prajwal says

    July 16, 2015 at 10:06 AM

    So simple and so beautifully explained. Thanks a lot. I really appreciate your work.

    Reply
  15. Tushar Budhlani says

    August 8, 2015 at 9:25 AM

    This article is really very helpful.
    Easy to understand.
    Systematic Explanation.
    I really appreciate those people who have worked on this.
    Great job!

    Reply
  16. shubham thakur says

    August 14, 2015 at 4:50 AM

    this site is very helpful 4 learning the basic concepts of java….the language is so simple dat anyone can easily understand this… seriously respect for the man behind this (Y)

    Reply
  17. Rahul Soni says

    August 19, 2015 at 10:06 AM

    This is really stunning site for getting knowledge of core fundamental of Java but you should come with Java Frameworks and ORM technology. Thanks

    Reply
  18. Shahan Shaffi says

    October 27, 2015 at 1:00 AM

    this site provides very helpful knowledge about the basic concepts of java

    Reply
  19. Rose says

    December 17, 2015 at 12:15 AM

    Thanks a lot
    It was really helpful to me for my exam
    Thank you so much

    Reply
  20. jafz says

    January 17, 2016 at 6:21 AM

    OOP concept needs be learnt like at ease like you have done. it’s indeed a good article to visulize a OOP properly.

    Reply
  21. Tonny Kirwa says

    February 15, 2016 at 8:35 AM

    I always refer to this website when I want to understand a given concept… Your work will live forever!

    Reply
  22. Smit says

    February 18, 2016 at 5:43 PM

    Hello Mr. Singh,
    I really fond of your deeds for beginners’. Your efforts and love been really appreciate. I have a small suggestion that it would be so good if you add pictures like stuff to explain the topics. Thank You.

    Reply
  23. Nitha says

    March 2, 2016 at 5:55 PM

    I have a question regarding protected access specifier.In this article it’s given that “protected: The scope of a protected variable is within the class which declares it and in the class which inherits from the class (Scope is Class and subclass)”. To my knowledge, Protected means Package level and Subclass level access(in Java). Could you please comment on this..
    Your articles are simple and very much helpful. Really appreciate your effort…
    Thank you

    Reply
  24. Peter says

    April 22, 2016 at 8:45 AM

    When I started learning Java Programming Language, I saw it as a very very complex thing. But this post has really helped me. I am enjoying learning Java. Do you have post for other programming languages like C, C++, Python, Pascal?

    Reply
  25. shubham says

    June 8, 2016 at 11:57 AM

    Can We Downlode PDF file of this OOP Concept, Please forward the Link if possible

    Reply
  26. Jeya Prakash says

    July 31, 2016 at 1:06 PM

    Super post for university assignment!

    Reply
  27. Rahul Jain says

    November 28, 2016 at 7:48 AM

    It is a best site to learn oops concept in very simple forms with suitable examples.And the content of this sites is easy to understand for learners.

    Reply
  28. Precious says

    January 14, 2017 at 9:47 PM

    This is a very explanatory article, it really helped. Thanks.

    Reply
  29. pavan says

    July 2, 2017 at 6:30 PM

    very useful artical for clearing basic concepts in our mind for interview ,
    thank you so much….

    Reply
  30. Lakshman says

    July 5, 2017 at 12:17 PM

    Hi Chaitanya,
    I liked the way of explanation you have given to all the topics with examples and I understood very well. I feel that this is the best site/blog I went through for Java.Thanks for that
    I have one suggestion that If there is a way to align the topics in an order to learn then it will be useful for new learners of Java.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap