AppDividend
Latest Code Tutorials

OOPs Concepts in Java Tutorial | Object Oriented Programming in Java

0

OOPs Concepts in Java Tutorial | Object Oriented Programming in Java is today’s topic. In this article, we will learn about Object Oriented Programming concepts. Object-Oriented Programming provides lots of ideas like Polymorphism, Abstraction, Encapsulations, etc. Simula is the first Object Oriented Programming though Smalltalk is considered as first fully Object-Oriented Programming.

Today there are lots of Object-Oriented Programming languages these are Java, C++, Python, PHP, C#, etc. The main motive of any Object-Oriented Programming language is to represent the real-world entity. Firstly, we need to understand more carefully about what is an object and what is the class. Now, let’s start OOPs Concepts in Java Tutorial With Example.

OOPs Concepts in Java Tutorial

Content Overview

Class in Java

Class is nothing but collections of objects. It helps us to create a blueprint of a particular object. Moreover, it does not consume memory.

 It represents a set of properties or methods that are common to all the objects of one type. In general, the class declarations can include the following components, in order.

  1. Modifiers: A class can have by default the default access.
  2. Class name: The name should begin with an initial letter (capitalized by convention).
  3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by a keyword extends. A class can only extend (subclass) one parent.
  4. Interfaces(if any): It is the comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. The class can implement more than one interface. Through Interface, we can implement the multiple inheritance.

Object in Java

As mentioned above, Object is a real-world entity such as the chair, table, pen, pencil, etc. It has both state and behavior and be physical or logical. I consume space. An object consists of :

  1. State: It is represented by attributes of the object. State reflects the properties of an object.
  2. Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects.
  3. Identity: It gives the unique name to an object and enables one object to interact with other objects.

Method in Java

A method is the collection of statements that perform some specific task and return the result to a caller. A method can perform some specific task without returning anything. Methods allow us to reuse code without retyping the code. In Java, every method must be part of some class which is different from other languages like C, C++, and Python. Methods are time savers and help us to reuse code without retyping the code.

Method Declaration

In general, method declarations has six components which are the following.

  1. Modifier-: Defines access type of the method i.e. from where it can be accessed in your application. In Java, there are 4 types of access specifiers.
    • public: It is accessible in all class in your application.
    • protected: It is accessible within the class in which it is defined and in its subclass(es)
    • private: It is accessible only within the class in which it is defined.
    • default (declared/defined without using any modifier): It is accessible within same class and package within which its class is defined.
  2. The return type: The data type of the value returned by the method or void if does not return the value.
  3. Method Name: The rules for field names apply to method names as well, but the convention is a little different.
  4. Parameter list: Comma-separated list of the input parameters is defined, preceded with their data type, within the unclosed parenthesis. If there are no arguments, you must use the empty parentheses ().
  5. Exception list: The exceptions you expect by a method can throw, you can specify these exception(s).

OOPs in Java

There are four main OOP concepts in Java Programming Language. These are Inheritance, Polymorphism, Encapsulation, and Abstraction. Now we are going to discuss one by one.

Inheritance in Java

Whenever an object inherits any property from another class, then it is known as Inheritance.

We use inheritance to increase the reusability of any program. Suppose if we are working on a big project using Java and there are lots of class and among these classes, we have methods. Now there a situation occurs where we need to use the same method again that has been declared before some classes. Now to reduce the memory of the program, we use Inheritance.

Let’s understand inheritance with the help of an example.

// Inheritance.java

//creating mammal class as parent class 
class Mammal
{
	void Identity()
	{
		System.out.println("It is a Mammal class");
	}
}
//exteding parent class
class Man extends Mammal
{
	void Category()
	{
		System.out.println("It is a Man class which extends Mammal");
	}
	
}


class Inheritance
{
	public static void main(String []er)
	{
		Man m =new Man();
		
		//accessing parent class method using child class object instance
		m.Identity(); 
		//accessing  chile class method
		m.Category();
	}
}

See the below output.

OOPs Concepts in Java Tutorial

 

Polymorphism in Java

Polymorphism is an ability of the object to take on many forms.

In Java, we use method overriding and method overloading to achieve polymorphism.

Now the question is, what is Method overriding?

It is a concept of OOP where the method of a child class can inherit the method of its parent class. It allows using one method in different ways depending on the object of child class or parent class.

Method Overloading is also a concept of Polymorphism where a single method can perfume different tasks depending on the context in which it’s called. It works in a different context for these we need to pass the different argument to it.

// Poly.java

//method overloading 
class Test
{
	//method with two arguments 
	int add(int a,int b)
	{
		return (a+b);
	}
	//method with three arguments
	int add(int a, int b, int c)
	{
		return (a+b+c);
	}
}
class Poly
{
	public static void main(String []er)
	{
		
		Test t= new  Test();
		System.out.println(t.add(1,2));//method with two argument will be calling
		System.out.println(t.add(1,2,3));//method with three argument will be calling
	}
}

See the below output. It is the example of Method Overloading in Java

 

Method Overloading in Java

Now, let’s write the program of Method Overriding in Java.

// Poly.java

class Vehicle
{

    public void move()
	{

      System.out.println("It moves");

    }

}

class Bike extends Vehicle
{

    //overriding the method of its parent class 
	public void move()
	{

     System.out.println("Bike moves and accelerates");

    }

}

class Poly2
{

    public static void main(String[] er)
	{

      Vehicle v=new Vehicle();
	//invoking parent class mehtod
      v.move();    

      v=new Bike();
		//invoking child class method 
      v.move();

    }

}

See the below output of Method Overriding.

Method Overriding in Java

Abstraction in Java

In OOP, Java is one of the most powerful concepts. Abstraction means to represent code in a sophisticated way so that it lets avoid repeating the same data.

Suppose, there is a method which is used to calculate average marks in a different class and that method is also used in another class, due to this requirement we use Abstraction. We achieve abstraction using Abstract method and interface in Java.

In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using Java Interfaces.

Let’s see an example to understand this Abstract better way. See the following code.

// Abstraction.java

//creating abstract class 
abstract class Mark
{
	// abstract method 
	abstract int avgMarks(int n);
}
//extending abstract class
class CSE extends Mark
{
	int avgMarks(int n)
	{
		return n;
	}
}
//extending abstract class 
class ME extends Mark
{
	// decaring abstract method
	int avgMarks(int a)
	{
		return a;
	}
}
//driver class
class Abstraction
{
	public static void main(String []er)
	{
	 CSE c=new CSE();
	 System.out.println(c.avgMarks(90));
	 ME m=new ME();
	 System.out.println(m.avgMarks(80));
	}
}

See the following output.

 

Abstraction in Java

Encapsulation in Java

Encapsulation is another one of the essential concepts in OOP. It also considered as the most powerful concept. It helps users to keep our data private from the user. To make private the data entered by the user, we have a setter method and to fetch the private data to show the user we have a getter method.

Let’s take an example to understand it better way. See the following code of encapsulation.

// Encap.java

class ATMCard
{
  private int pin;
  void setPin(int pin)
  {
	this.pin=pin;  
  }
  int getPin()
  {
	  return pin;
  }
}
class Encap
{
	public static void main(String []er)
	{
		ATMCard c=new ATMCard();
		c.setPin(1234);
		System.out.println(c.getPin());
	}
}

See the below output.

Encapsulation in Java

Best Practices for OOP Concepts in Java

  1. DRY (Don’t Repeat Yourself). It is the core concept of OOP Language. You should never have two blocks of identical code in two different places. Instead, you can have one method you use that method for different applications.
  2. If you expect your Java code to change in the future, encapsulate it by making all the variables and methods private at the outset. As a code changes, increase access to protected” as needed, but not too public. It is bad practice to turn all your code to the public.
  3. Single Responsibility. Another best practice for writing the applications in Java is the Single Responsibility Principle. A class should always have only one functionality, it can’t be responsible for more than one task. That way, it can be called and/or extended on its own when new uses arise for it, without causing the coupling between different functionalities.
  4. Open Closed Design. Make all the methods and classes closed for modification but open for the extension. That way, your tried and tested code can remain static but can be modified further to perform as new tasks added in the future.

Finally, OOPs Concepts in Java Tutorial | Object Oriented Programming in Java post is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.