{"id":171,"date":"2024-09-03T15:41:01","date_gmt":"2024-09-03T10:11:01","guid":{"rendered":"https:\/\/itvedant.com\/blog\/?p=171"},"modified":"2025-06-27T14:31:06","modified_gmt":"2025-06-27T09:01:06","slug":"write-reusable-code-in-java","status":"publish","type":"post","link":"https:\/\/www.itvedant.com\/blog\/write-reusable-code-in-java\/","title":{"rendered":"How to Write Reusable Code in Java?"},"content":{"rendered":"\n<p>Java is an object-oriented programming language with features such as classes, objects, inheritance, polymorphism abstraction, encapsulation, exception handling, multithreading, security, etc. By using these we can build an application that is modular, manageable, and robust.<\/p>\n\n\n\n<p>An application is a collection of multiple classes, interfaces, APIs, etc that work in conjunction to give required functionality. During the software development process, many times we might need to use a particular block of code multiple times in the application\u2019s logic so, creating reusable code promotes code efficiency, reduces redundancy and simplifies maintenance.<\/p>\n\n\n\n<p>Reusable code is designed to be used across multiple projects or within different parts of the same project without modification. Features like methods, and inheritance allow to write a reusable blocks of code that can be used in the application.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Guide To Write Reusable Code in Java<\/h2>\n\n\n\n<p>In Java we can write reusable codes by using the following techniques:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Encapsulation<\/li>\n\n\n\n<li>Inheritance\u00a0<\/li>\n\n\n\n<li>Interfaces\u00a0<\/li>\n\n\n\n<li>Generics<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">1. Encapsulation<\/h3>\n\n\n\n<p>Encapsulation is the process of wrapping up data members and member functions into a single unit for instance class. With the help of encapsulation, the internal state of the data members can be hidden and given controlled access via methods.<\/p>\n\n\n\n<p>These methods are usually the getter and setter methods. The setter method is used to provide\/ set value to data members and the getter method is used to retrieve the set value.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example:<\/h4>\n\n\n\n<p><strong>Person.java<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example;\n\npublic class Person {\n\n\/\/ data members\n\nprivate int age;\n\nprivate String name;\n\nprivate String email;\n\n\/\/ constructors\n\npublic Person() {}\n\npublic Person(String name, int age, String email) {\n\nthis.name = name;\n\nthis.age = age;\n\nthis.email = email;\n\n}\n\n\/\/ getters and setters\n\npublic int getAge() {\n\nreturn age;\n\n}\n\npublic void setAge(int age) {\n\nthis.age = age;\n\n}\n\npublic String getName() {\n\nreturn name;\n\n}\n\npublic void setName(String name) {\n\nthis.name = name;\n\n}\n\npublic String getEmail() {\n\nreturn email;\n\n}\n\npublic void setEmail(String email) {\n\nthis.email = email;\n\n}\n\n\/\/toString to display object information\n\n@Override\n\npublic String toString() {\n\nreturn \"person information : &#91;\" + getName() + \" : \u00a0 \u00a0 \u00a0 \" + getAge() + \" : \" + getEmail() + \"]\";\n\n}\n\n}<\/code><\/pre>\n\n\n\n<p><strong>TestPerson1.java<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example;\n\npublic class TestPerson1 {\n\npublic static void main(String&#91;] args) {\n\nPerson p = new Person();\n\np.setName(\"kalyani\");\n\np.setAge(30);\n\np.setEmail(\"kalyani@itvedant.com\");\n\nSystem.out.println(p);\n\n}\n\n}<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong>&nbsp;<\/p>\n\n\n\n<p>person information : [kalyani : 30 :&nbsp; kalyani@itvedant.com]<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Explanation<\/h5>\n\n\n\n<p>In the above example, the Person class contains name, email and age data members and constructors and getters and setters. These methods can be used in any class to get-set a person\u2019s information.<\/p>\n\n\n\n<p>In TestPerson1.java we created a reference of the Person class and provided values to the data members using the setter methods and overridden the toString() method to display the person object information. We passed the person object \u2018p\u2019 directly to the print statement which using the toString() displays the person object information.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. Inheritance<\/h3>\n\n\n\n<p>Inheritance refers to the process of acquiring some or all properties and behaviour of an existing class into a newly created class. The newly created class may have its own properties and behaviour too.<\/p>\n\n\n\n<p>Inheritance involves method overriding which is a process of overriding the methods of the parent class into the child class. Here, the parent class refers to the super\/ root\/ base class and the child class refers to the sub\/ leaf\/ derived class.<\/p>\n\n\n\n<p>In Java Inheritance can be used by extending the child class from the parent class. The keyword used is \u201cextends\u201d. Every class, be it a predefined class or user-defined class extends to the rootmost class Object. In Java following types of inheritance are supported:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Single Level\u00a0<\/li>\n\n\n\n<li>Multi-Level<\/li>\n\n\n\n<li>Hierarchical Level<\/li>\n<\/ol>\n\n\n\n<h4 class=\"wp-block-heading\">Single Level Inheritance Example:<\/h4>\n\n\n\n<p>For this example, we will use the Person.java class built in the Encapsulation example.&nbsp;<\/p>\n\n\n\n<p><strong>Student.java<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example;\n\npublic class Student extends Person{\n\nprivate int rollno;\n\nprivate String course;\n\npublic Student(){}\n\npublic Student(String name, int age, String email, int rollno, String course) {\n\nsuper(name, age, email);\n\nthis.rollno = rollno;\n\nthis.course = course;\n\n}\n\npublic int getRollno() {\n\nreturn rollno;\n\n}\n\npublic void setRollno(int rollno) {\n\nthis.rollno = rollno;\n\n}\n\npublic String getCourse() {\n\nreturn course;\n\n}\n\npublic void setCourse(String course) {\n\nthis.course = course;\n\n}\n\npublic void displayCourseFees(String course) {\n\nif(course.equals(\"Full-Stack\")) {\n\nSystem.out.println(\"Fees : Rs50000\");\n\n}\n\nelse if(course.equals(\"Data-Science\")) {\n\nSystem.out.println(\"Fees : Rs53000\");\n\n}\n\nelse {\n\nSystem.out.println(\"Course Not Available\");\n\n}\n\n}\n\n@Override\n\npublic String toString() {\n\nreturn super.toString() + \" : \" + getRollno() + \" : \" + getCourse();\n\n}\n\n}<\/code><\/pre>\n\n\n\n<p><strong>TestStudentInheritance.java<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example;\n\npublic class TestStudentInheritance {\n\npublic static void main(String&#91;] args) {\n\nStudent stud = new Student();\n\nstud.setName(\"Akash\");\n\nstud.setAge(30);\n\nstud.setEmail(\"akashdinde92@gmail.com\");\n\nstud.setRollno(112);\n\nstud.setCourse(\"Full-Stack\");\n\nSystem.out.println(stud);\n\nstud.displayCourseFees(stud.getCourse());\n\n}\n\n}<\/code><\/pre>\n\n\n\n<p><strong>Output:&nbsp;<\/strong><\/p>\n\n\n\n<p><strong><\/strong>person information : Akash : 30 : akashdinde92@gmail.com : 112 : Full-Stack<\/p>\n\n\n\n<p>Fees : Rs50000<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong><\/strong>Explanation<\/h5>\n\n\n\n<p>In this example, we inherited the Student class from the existing Person class. In the Student class, we added roll no and course data members. For these, we created getters and setters.<\/p>\n\n\n\n<p>In the Student constructor, we first gave a call to the Person class constructor using super() to reuse the Person constructor logic and then assigned the values to roll no and course during the object creation.<\/p>\n\n\n\n<p>The Student class has a displayCourseFees() method which is used to display the fees for Full-Stack and Data-Science students. The toString() method is used to return the Person class content using super.toString() and the Student class content.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3. Interfaces<\/h3>\n\n\n\n<p>An Interface is a mechanism used to achieve abstraction in Java. Now, Abstraction refers to a process of hiding the implementation details from the user and giving only the essential details\/ functionality to the user.<\/p>\n\n\n\n<p>The interface provides a contract to the implementing classes where the methods provided by the interface can be given logic by the classes. The interface contains constants and only method prototypes, in simple words interface is a collection of fixed values and abstract methods.&nbsp;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Example&nbsp;<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>Interface : Drawable.java\n\npackage com.example;\n\npublic interface Drawable {\n\nvoid drawCircle(int radius);\n\n}\n\nClass implementing Drawable Interface :\u00a0\n\npackage com.example;\n\npublic class DrawShapes implements Drawable {\n\npublic static void main(String&#91;] args) {\n\nint radius = 2;\n\nDrawShapes draw = new DrawShapes();\n\ndraw.drawCircle(radius);\n\n}\n\n@Override\n\npublic void drawCircle(int radius) {\n\nSystem.out.println(\"Drawing circle of radius \" + radius);\n\n}\n\n}<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<p>Drawing circle of radius 2<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Explanation<\/h5>\n\n\n\n<p>In the above example, the Drawable interface consists of the drawCircle(int radius) method. Now, The class DrawShapes implements the interface Drawable so it becomes the responsibility of the class to give the drawCircle() methods logic.&nbsp;<\/p>\n\n\n\n<p>Interfaces provide 100% of abstraction.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Generics<\/h3>\n\n\n\n<p>Generics refers to parameterized types. The major aim behind using generics is that it allows types such as Integer, String, Byte or any User-Defined type can be passed as parameters to methods or classes or interfaces.&nbsp;<\/p>\n\n\n\n<p>With the help of generics, a template can be created which can be utilized for a variety of data types. These are the same as the Templates of CPP.<\/p>\n\n\n\n<p>Generic Methods, Classes and Interfaces can be created. Here, we will consider the example of Generic classes which work on multiple types of data.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Exampleused to retrieve the set value.<\/h4>\n\n\n\n<p><strong>Box.java<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example;\n\npublic class Box&lt;T> {\n\nprivate T type;\n\npublic void put(T item) {\n\nthis.type = item;\n\n}\n\npublic T get() {\n\nreturn type;\n\n}\n\n}<\/code><\/pre>\n\n\n\n<p><strong>TestGenerics.java<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example;\n\npublic class TestGenerics {\n\npublic static void main(String&#91;] args) {\n\nBox&lt;Integer> intData = new Box&lt;>();\n\nintData.put(100);\n\nSystem.out.println(\"Integer data : \" + intData.get());\n\nBox&lt;String> stringData = new Box&lt;>();\n\nstringData.put(\"ITVedant\");\n\nSystem.out.println(\"String data : \" + stringData.get());\n\n}\n\n}<\/code><\/pre>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<p>Integer data : 100<\/p>\n\n\n\n<p>String data : ITVedant<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Explanation<\/h5>\n\n\n\n<p>In the above example, the Box class is created as a base template class which can be used to set different types. The put() method is used to set the box type to the respected data type and the get() method is used to retrieve the value that is set to the box type. Initially, the Box is put to Integer type and provided value 100 and then it is put to String type and provided value ITVedant.<\/p>\n\n\n\n<p>This way we can use Encapsulation, Inheritance, Interfaces and Generics for code reusability.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why is it Important to Write Reusable Code?<\/h2>\n\n\n\n<p>There are many reasons why writing reusable codes is important and how they help in effective software development:&nbsp;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. Efficiency and Productivity<\/h3>\n\n\n\n<p>The usage of reusable code allows the developers to save the time and effort of writing the same code again and again in different parts of the application. Due to this productivity and efficiency increase.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. Reduced Duplicacy<\/h3>\n\n\n\n<p>Since we will use the already written code blocks, the duplication of code is removed. The boilerplate code especially is removed by using reusable codes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3. Consistency and Uniformity<\/h3>\n\n\n\n<p>Reusing code promotes consistency in the application development process. So changes made in the original code block will be applied to the reused code blocks as well. This helps in maintaining uniformity across the whole application being developed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4. Code Readability and Maintainability<\/h3>\n\n\n\n<p>Writing reusable codes helps in making the codebase more modular and encapsulated. This leads to a cleaner and more maintainable codebase. Developers can easily understand and modify the existing components without getting into details.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">5. Ease of Testing<\/h3>\n\n\n\n<p>The reusable block of codes can be tested individually before reusing them. This helps in finding errors at the early stages. Thus saving time required in the testing process.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">6. Best Practices<\/h3>\n\n\n\n<p>Writing reusable code blocks is one of the major best practices that we can incorporate in our application development process. This makes the codebase more manageable and readable.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>The writing of <a href=\"https:\/\/dl.acm.org\/doi\/pdf\/10.1145\/258368.258397\">reusable code<\/a> is one of the fundamental practices in the software development process which enhances efficiency, maintainability and also the quality of the software being developed.<\/p>\n\n\n\n<p>By creating reusable code blocks, the developers can reduce efforts, time and duplicity in development and promote consistency and uniformity across the whole application. This approach leads to a more lean, clean code writing and makes the application codebase more modular. If you\u2019re planning to become a Java developer, it\u2019s time to check out our <a href=\"https:\/\/www.itvedant.com\/java-full-stack-developer-course\">Java Course with 100% Job Guarantee<\/a><br>Want to learn how to create portable and dependable code in Java? Read: <a href=\"https:\/\/www.itvedant.com\/java-write-once-run-anywhere\">WORA in Java<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Java is an object-oriented programming language with features such as classes, objects, inheritance, polymorphism abstraction, encapsulation, exception handling, multithreading, security, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":248,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[11],"tags":[],"class_list":["post-171","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java"],"_links":{"self":[{"href":"https:\/\/www.itvedant.com\/blog\/wp-json\/wp\/v2\/posts\/171"}],"collection":[{"href":"https:\/\/www.itvedant.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.itvedant.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.itvedant.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.itvedant.com\/blog\/wp-json\/wp\/v2\/comments?post=171"}],"version-history":[{"count":5,"href":"https:\/\/www.itvedant.com\/blog\/wp-json\/wp\/v2\/posts\/171\/revisions"}],"predecessor-version":[{"id":177,"href":"https:\/\/www.itvedant.com\/blog\/wp-json\/wp\/v2\/posts\/171\/revisions\/177"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.itvedant.com\/blog\/wp-json\/wp\/v2\/media\/248"}],"wp:attachment":[{"href":"https:\/\/www.itvedant.com\/blog\/wp-json\/wp\/v2\/media?parent=171"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.itvedant.com\/blog\/wp-json\/wp\/v2\/categories?post=171"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.itvedant.com\/blog\/wp-json\/wp\/v2\/tags?post=171"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}