×

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture.

JAVA SOLID PRINCIPLES

Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed the discipline of object-oriented programming and the process of creating software.  It ensures that the software is refactorable, debuggable, and modular.

S: Single responsibility principle

O: Open-closed principle

L: Liskov substitution principle

I: Interface segregation principle

D: Dependency inversion principle

Advantages of Solid Principles

  • Code is standardized and easy
  • Easy to maintain
  • Code can be easily tested
  • Code is independent and reusable
  • There will be no redundancy in code

Single responsibility principle

The single responsibility principle says that a class should perform only one method or function. It does not imply that the class should not have more functions, but it is recommended to perform one function.

Example single responsibility principle

If you have a class with the name Film that contains three methods like shooting(), Editing() and Release().

Program without using the single responsibility principle

Film.java

class Film
{
public void Shooting()
{
System.out.println(“Shooting method”);
// shotting action
}
public void Editing()
{
// Editing action
System.out.println(“Editing method”);
}
public void Release()
{
// release
System.out.println(“Release method”);
}
Public static void main(String s[])
{
//Main function
}
}

Explanation

In the above sample code, there is a class Film with 3 actions that perform 3 different actions. Having all the functions in one class is making the code complex. So, according to the single responsibility principle, we will separate each function into separate classes.

Program using single responsibility principle

Film.java

class Film
{
public void Shooting()
{
// shotting action
}
public static void main(String s[])
{
    // main method
}
}

Edit.java

class Main
{
public void Editing()
{
// Editing action
}
public static void main(String s[])
{
    // main method
}
}

Release.java

class Release
{
public void Release()
{
// release function
}
public static void main(String s[])
{
    // main method
}
}

Explanation

In the above sample code,  all the three functions have 3 separate classes according to the single responsibility principle.

Advantages

  • Easy to test and compile
  • fewer dependencies
  • Code is organized

Open Closed Principle

A class should be designed by this theory so that it completes its purpose successfully without the need for future modification. As a result, it should be feasible to expand the class but it should remain closed to modification.

Methods to do Open closed principle are

1. Using Inheritance
2. Extending class behavior

Program using the open-closed principle

MultiInherit.java

interface Father
{
float ht=6.2f;
void height();
}
interface Mother
{
float ht=5.8f; // public static final variable
void height(); //public abstract method
}
class Child implements Father, Mother
{
public void height()
{
//child got average height of  parents
float ht=(father.ht+mother.ht)/2;
System.out.println("child's height: " +ht);
}
}
class MultiInherit
{
public static void main(String args[])
{
Child c1 = new Child();
c1.height();
}//main
}

Liskov Substitution Principle

The derived classes must be fully interchangeable with their source classes when it comes to inheritance. In other words, if class A is a subtype of class B, we should be able to substitute A for B without having the program behave differently.

Program for Liskov Substitution principle

public class Student   
{  
 int height;  
 int weight;  
public void setHeight(double h)   
    {   
        height = h;   
    }  
public void setWeight(double w)   
    {   
        weight= w;   
    }  
}  
public class StudentBMI extends Student  
{  
public void setHeight(double h)   
    {  
super.setHeight(h);  
super.setWeight(w);  
    }  
public void setWeight(double h)   
    {  
super.setHeight(h);  
super.setWeight(w);  
    }  
}  

Interface Segregation Principle

According to the idea, bigger interfaces break into smaller ones. because the implementation classes only employ the necessary methods. This principle is similar to the single popularity principle.

Example

Syntax:

public interface Vehicle  
{  
public void car();  
public void bus();  
public void train();  
}  

In the above, all three methods are stored in a single interface. By using the Interface Segregation principle we can split the interface methods.

Syntax:

public interface Converion1
{  
public void car();  
}   
public interface Conversion2
{  
public void bus();  
}  
public interface Conversion3   
{  
public void train();  
}  

Program for Interface segregation principle

public class Conversion implements IntToDouble,CharToString   
{  
public void intToDouble()  
{  
    // method 
   // integer to double
}  
public void charToString()  
{  
    //conversion logic  
    // character to string function
}  
}  

Dependency inversion principle

 It states that the code should depend on abstract details as a substitute for concrete details. We can design software in such a way that various packages or modules are separated from each other by using an abstract layer to bind them together. This principle can be used as classical use in the view of spring framework, All spring frameworks have separate components, these can be worked by injecting dependencies.

     Here, Injection is nothing but a process of passing dependencies to a dependency object.

Dependency Injection:

It is a design pattern, that implements the inversion control of dependencies.

It allows programmers to remove Hard-coded dependencies so that the application is made extendable.

Example

Syntax

public class Employee
{
  private Details details
 public class Employee ()
{
      details = new Details ();
}
}

In the above code, the Employee requires the Details object and it is useful to initialize the Details object. If the Details class is changed at any time, then we can also make changes in the Employee class. This makes a tight coupling between the Details class and the Employee class. This problem can be solved by the dependency inversion principle i.e, the Details object will be implemented independently and it is provided to the Employee class.


Related Topics

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.