×

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 doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 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.

Java Implements Keyword

To understand about the keyword implements we need to learn about the concept of the interfaces and inheritance in java programming languages. So let us learn about the interface and...

3 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Differences between Byte Code and Machine Code

This tutorial will discuss the differences between Byte Code and Machine Code. Before that, let's try to know what byte and machine code is. Introduction Every computer has a set of instructions...

4 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Memory Leak in Java

Java offers memory management right out of the box. When we use the new keyword to create an object, the JVM initialises for that object immediately. The trash collector automatically...

3 minutes read.