OOPS Concepts in Java – OOPS Concepts Example

Filed Under: Java

OOPS Concepts or Object-Oriented Programming Concepts are very important. Without having an idea about OOPS concepts, you will not be able to design systems in the object-oriented programming model.

OOPS Concepts

oops concepts, object oriented programming concepts, oops concepts in java

Core OOPS concepts are:

  1. Abstraction
  2. Encapsulation
  3. Polymorphism
  4. Inheritance
  5. Association
  6. Aggregation
  7. Composition

Let’s look into these object-oriented programming concepts one by one. We will use Java programming language for code examples so that you know how to implement OOPS concepts in java.

Abstraction

Abstraction is the concept of hiding the internal details and describing things in simple terms. For example, a method that adds two integers. The internal processing of the method is hidden from the outer world. There are many ways to achieve abstraction in object-oriented programmings, such as encapsulation and inheritance.

A Java program is also a great example of abstraction. Here java takes care of converting simple statements to machine language and hides the inner implementation details from the outer world.

Encapsulation

Encapsulation is the technique used to implement abstraction in object-oriented programming. Encapsulation is used for access restriction to class members and methods.

Access modifier keywords are used for encapsulation in object oriented programming. For example, encapsulation in java is achieved using private, protected and public keywords.

Polymorphism

Polymorphism is the concept where an object behaves differently in different situations. There are two types of polymorphism – compile time polymorphism and runtime polymorphism.

Compile-time polymorphism is achieved by method overloading. For example, we can have a class as below.


public class Circle {

	public void draw(){
		System.out.println("Drwaing circle with default color Black and diameter 1 cm.");
	}
	
	public void draw(int diameter){
		System.out.println("Drwaing circle with default color Black and diameter"+diameter+" cm.");
	}
	
	public void draw(int diameter, String color){
		System.out.println("Drwaing circle with color"+color+" and diameter"+diameter+" cm.");
	}
}

Here we have multiple draw methods but they have different behavior. This is a case of method overloading because all the methods name is same and arguments are different. Here compiler will be able to identify the method to invoke at compile-time, hence it’s called compile-time polymorphism.

Runtime polymorphism is implemented when we have “IS-A” relationship between objects. This is also called a method overriding because subclass has to override the superclass method for runtime polymorphism.

If we are working in terms of the superclass, the actual implementation class is decided at runtime. The compiler is not able to decide which class method will be invoked. This decision is done at runtime, hence the name as runtime polymorphism or dynamic method dispatch.


package com.journaldev.test;

public interface Shape {

	public void draw();
}

package com.journaldev.test;

public class Circle implements Shape{

	@Override
	public void draw(){
		System.out.println("Drwaing circle");
	}

}

package com.journaldev.test;

public class Square implements Shape {

	@Override
	public void draw() {
		System.out.println("Drawing Square");
	}

}

Shape is the superclass and there are two subclasses Circle and Square. Below is an example of runtime polymorphism.


Shape sh = new Circle();
sh.draw();

Shape sh1 = getShape(); //some third party logic to determine shape
sh1.draw();

In the above examples, java compiler doesn’t know the actual implementation class of Shape that will be used at runtime, hence runtime polymorphism.

Inheritance

Inheritance is the object-oriented programming concept where an object is based on another object. Inheritance is the mechanism of code reuse. The object that is getting inherited is called superclass and the object that inherits the superclass is called subclass.

We use extends keyword in java to implement inheritance. Below is a simple example of inheritance in java.


package com.journaldev.java.examples1;

class SuperClassA {

	public void foo(){
		System.out.println("SuperClassA");
	}
	
}

class SubClassB extends SuperClassA{
		
	public void bar(){
		System.out.println("SubClassB");
	}
	
}

public class Test {
	public static void main(String args[]){
		SubClassB a = new SubClassB();
		
		a.foo();
		a.bar();
	}
}

Association

Association is the OOPS concept to define the relationship between objects. The association defines the multiplicity between objects. For example Teacher and Student objects. There is a one-to-many relationship between a teacher and students. Similarly, a student can have a one-to-many relationship with teacher objects. However, both student and teacher objects are independent of each other.

Aggregation

Aggregation is a special type of association. In aggregation, objects have their own life cycle but there is ownership. Whenever we have “HAS-A” relationship between objects and ownership then it’s a case of aggregation.

Composition

The composition is a special case of aggregation. The composition is a more restrictive form of aggregation. When the contained object in “HAS-A” relationship can’t exist on its own, then it’s a case of composition. For example, House has-a Room. Here the room can’t exist without the house. Composition is said to be better than inheritance, read more at Composition vs Inheritance.

Further Reading: Composition in Java

That’s all for a quick round-up on OOPS concepts.

You can go through more Java example programs from our GitHub Repository.

References: https://docs.oracle.com/javase/tutorial/java/concepts/

Comments

  1. Ashok Burania says:

    Super….. Thanks Pankaj

  2. Bruno says:

    Hi Pankaj, thank you very much for so much information about Java and all in the same place. It was great idea doing that. I have read lots of your articles.
    Allow me to point something that doesn’t sound right, when you say:
    “Shape is the superclass and there are two subclasses Circle and Square.” shouldn’t it be:
    “Shape is an interface and Circle and Square are implementations of it, which give us an Interface polymorphism.” ?

    1. Pankaj says:

      The idea here is to show the inheritance. The Shape can also be a class and Circle/Square classes extend it.

  3. Boss shivaji the boss says:

    nice very very nice i love it.. ha ha ha ha

  4. preeti says:

    Thank you for sharing such an informative and useful post with us.

  5. Senuja Ranhira says:

    excellent,super

  6. Sudeep says:

    Very simple and nice

    1. Baby sabia mendoza says:

      How to answer this code
      ****
      ***
      **
      *

  7. priya karthi says:

    Thanks for the simple and wonderful explanations. Can you please add examples for association, aggregation and compositions as well? That would be very helpful.

  8. Shahzad Khan says:

    Nice Article Bro , It could help me In my Interview <3

  9. online java training says:

    I found this article useful & informative. The whole concept of OOPS in Java was explained beautifully with the help of such good examples so that it’s very easy to understand for me. Nice sharing.

  10. Noorulhaq sharifi says:

    Thanks a bunch because it was explained very simply and very useful

  11. Sonam Sehgal says:

    Thanks. very well explained,

  12. Madhu says:

    Nice Arcticle, Well explained with examples

  13. Prateek says:

    Nice explanation with great examples. Loved it

  14. Reshma Ullas says:

    Thank you , Nice article.

  15. Anusha says:

    Can you please explain about Coupling and Cohession?

    1. Tharaka Wijerama says:

      I only know one thing about your question. At the software engineering industry, according to modern software development concepts, all developed software should be highly cohesive and loosely coupled.

    2. Rakesh Parmar says:

      Cohesion refers to what the class (or module) can do. Low cohesion would mean that the class does a great variety of actions – it is broad, unfocused on what it should do. High cohesion means that the class is focused on what it should be doing, i.e. only methods relating to the intention of the class.

      As for coupling, it refers to how related or dependent two classes/modules are toward each other. For low coupled classes, changing something major in one class should not affect the other. High coupling would make it difficult to change and maintain your code; since classes are closely knit together, making a change could require an entire system revamp.

  16. Hashim.TA says:

    Nice ariticle,realy its cativative.
    Each sentences are simple and .understandable..
    I used this article for my assignnent purposes for the reference and realy it is awosome.
    Thumps up 🙂

  17. Omkar Kulkarni says:

    nice short but sweet explanations with real time examples helping to visualize concepts

  18. Shaheen says:

    I like it

    1. Mayuri says:

      Thank you for article.can you explain difference between composition and aggregation with example?

  19. vishnuvarthan says:

    many ways to achieve abstraction in object oriented programming, such as encapsulation and inheritance. this is corrects by inheritance are interface

  20. indrajit kumar says:

    after reading your articles about design pattern and OOPS It’s Very clear and helpful please provide such type articles on DFD SRS ER diagram use case diagram and so on..

  21. Arun SIngh says:

    helpful

  22. Madheshwaran says:

    Really i am happy with this article now i cleared oops Concept. i ll refer this site who has going to learn Java or Oops Concept this ll help a lot. I ll special thank to this article owner

    Thank you,

  23. pranit says:

    excellent article! You have shared each and every point of OOPs concept very well and precise, its easy to understand every term you have explained here. Fine and clearly explained list of OOPs concept in java. Thanks a lot for sharing!

  24. Khushi says:

    Thanks…superb

    1. k.vijaya says:

      oops concept is clearly understood because of this article
      thank you for sharing like this articles.

  25. krishna kanth says:

    well define

  26. RAJENDRAPRASAD says:

    SUPER AND CLEAR

  27. sahaana says:

    The topics are very clear…

  28. Naveen Sneha says:

    Helpful and very meaningful.

    Thanks dear friend Naveen

  29. Ganesh says:

    nice bro

  30. Ramakrishna Reddy says:

    simply superbbb

  31. Saurabh kaushal says:

    Good and simple for understanding the meaning of containt…thank for your kind

  32. Thrimurthulu says:

    excellent, it is very neat and clean.

  33. sai ranga talari says:

    clear and clean… thank u so much 🙂

  34. ravi says:

    Really super . it is very neat and clean.

  35. vivek says:

    Really excellent with simple words

  36. Ramesh says:

    Nice. Good for refreshment. Thanks Ramesha

  37. reemza says:

    After read all of your articles about design pattern and OOP, i can say that you know how to choose the right word to explain thing. Very clear, precise and easy to understand and follow.

    Thumbs up.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages