How to Create Custom Class in Java?


In Java, a class is a fundamental component of object-oriented programming. It serves as a blueprint or template for defining the structure and behavior of objects. A class contains both data, represented by fields or variables, and behaviors, represented by methods or functions, which manipulate that data.

In Java, a custom class is a user-defined class that allows you to create objects with specific properties and behaviors tailored to your application's requirements. It serves as a blueprint or template for creating objects of that class type. Custom classes encapsulate related data and operations into a single entity, promoting code organization, reusability, and maintainability.

To create a custom class in Java, you typically define its structure, properties (also known as instance variables), and methods (functions that perform actions or provide functionality).

Key Components of Custom Class

  • Class Declaration − The class declaration defines the name of the class and any access modifiers (e.g., public, private) that control its visibility.

Syntax

accessModifier class ClassName
  • Instance Variables − These variables represent the attributes or properties of an object. They define the state or data associated with each instance of the class. Instance variables are typically declared at the class level but are specific to each instance of the class.

Syntax

accessModifier dataType variableName;
  • Constructors − It is called automatically when an object is created with the help of a new keyword and is responsible for setting the initial state of the object.Constructors share the same name as the class they belong to.and can take parameters to set initial values for the instance variables.

Syntax

accessModifier ClassName(parameters) { ... }
  • Methods − Methods define the behavior and operations that can be performed on objects of the class. They encapsulate code and allow you to perform actions or provide functionality. Methods can have return types (or void if they don't return anything) and can take parameters.

Syntax

accessModifier returnType methodName(parameters) { ... }
  • Access Modifiers − Access modifiers control the visibility and accessibility of classes, variables, and methods. The main access modifiers in Java are public, private, and protected. They determine whether other classes can access or modify the class members.

  • Getters and Setters − Getters and setters are special methods used to access and modify the values of private instance variables.

Example 1

The following program demonstrates about custom class in java

//Java program that demonstrates about creation of custom class in java
class StudentReport {
   private String student_name;
   private int student_age;
   private double marksObtained;
   private char student_grade;
 
   public StudentReport(String name, int age, double marks) {
      this.student_name = name;
      this.student_age = age;
      this.marksObtained = marks;
   }
 
   public void calculateGrade() {
      if (marksObtained >= 90) {
         student_grade = 'A';
      } else if (marksObtained >= 80) {
         student_grade = 'B';
      } else if (marksObtained >= 70) {
         student_grade = 'C';
      } else if (marksObtained >= 60) {
         student_grade = 'D';
      } else {
         student_grade = 'F';
      }
   }
 
   public void displayInfo() {
      System.out.println("Name: " + student_name);
      System.out.println("Age: " + student_age);
      System.out.println("Marks: " + marksObtained);
      System.out.println("Grade: " + student_grade);
   }
}
 
public class Testing {
 
   public static void main(String args[]){
      System.out.println("STUDENT DETAILS");
      System.out.println("===============\n");
      StudentReport s1=new StudentReport("Hari",21,90);
      s1.calculateGrade();
      s1.displayInfo();
      System.out.println();
      StudentReport s2=new StudentReport("Syam",20,92);
      s2.calculateGrade();
      s2.displayInfo();
   }
}

Output

STUDENT DETAILS
===============
Name: Hari
Age: 21
Marks: 90.0
Grade: A

Name: Syam
Age: 20
Marks: 92.0
Grade: A

Example 2

The following program demonstrates about custom class in java

class UserDetails {
   private String userName;
   private String userEmail;
   private String userPwd;

   public UserDetails(String username, String email, String password) {
      this.userName = username;
      this.userEmail = email;
      this.userPwd = password;
   }

   public void displayUserInfo() {
      System.out.println("Username: " + userName);
      System.out.println("Email: " + userEmail);
   }

   //this function checks whether password
   //that is same with the one's that is passed during user object   creation
   public boolean isPasswordCorrect(String inputPassword) {
      return userPwd.equals(inputPassword);
   }
}

public class Testing {

   public static void main(String args[]){
      System.out.println("USER DETAILS");
      System.out.println("===============\n");
      UserDetails u1=new UserDetails("Hari","abc@gmail.com","abc123");
      u1.displayUserInfo();
      System.out.println("Password Matched:"+u1.isPasswordCorrect("abc123"));
   }
}

Output

USER DETAILS
===============
Username: Hari
Email: abc@gmail.com
Password Matched:true

Advantages of Custom Classes

  • Modularity and Code Organization − Custom classes allow you to encapsulate related data and functionality into a single entity. This promotes code modularity and organization, making your code more readable.

  • Extensibility − Custom classes can be extended and subclassed to add or modify functionality. This allows you to build upon existing classes, inherit their properties and methods, and customize them to suit specific needs.

Disadvantages of Custom Classes

  • Increased Complexity − Using custom classes introduces additional complexity to your codebase. You need to define and manage class structures, handle interactions between different classes, and ensure proper data flow.

  • Overhead and Memory Usage − Each instance of a custom class requires memory allocation, which may lead to increased memory usage, especially when dealing with a large number of objects.

Conclusion

In this article we have seen how to create custom classes in java. Custom classes are widely used in Java development and offer numerous benefits, but they should be designed, used, and maintained effectively to maximize their advantages and minimize potential drawbacks.

Overall, custom classes provide a way to organize and structure your code, promote code reusability, and enable object-oriented programming paradigms in Java.

Updated on: 16-Oct-2023

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements