Constructors and Encapsulation In Java

We started learning object-oriented programming in Java, now we ready to move on to a new subject. We’ll learn constructors and encapsulation.

In this article, we’ll start with what is constructors and encapsulation so we’ll learn the theory of these two concepts for preparation. Then we’ll learn how to use these concepts in a real project.

What are Constructors?

Constructors are used to invoking objects with arguments. When the class is run, the first Constructors run. Shortly, before call class, we can assign a value for someone variable with constructors.

Constructors Syntax
public class MainClass
   public MainClass(arg...)
      // Code Here

The syntax of constructors is very simple. They are created in the same header as the main class, and they do not take any identifiers.

What is Encapsulation?

We use private users to hide data that should remain confidential, and we can use getter and setter to access this data.

This method or system, It helps us to store data that we do not want to reach us. We can also make these available to private users only.

It may sound like a password program right now, but no, it is very easy to understand even though it does not have a very short syntax, you can give read or write access to the people. Let’s examine it.

Encapsulation Syntax
private int x = 0;

public int getId()
   return id;

public void setId(int x)
   id = x;

There are two main functions in the simplified syntax, one for reading and one for writing. You can assign a new value with SetId, read the value with getId.

2 Concept In 1 Project

Anymore, we learned these concepts let’s do exercise with these concepts. This console project is a site membership system, we call the password of the member of the site with the encapsulation method, and we will use a constructor in the created user class.

// Main Code
public static void main(String[] args)
 UserManager newUser = 
 new UserManager("Kayra" , "QWERTY12345");

 String pass = newUser.getPass();
public class UserManager
 private String username;
 private String pass;

 public UserManager(String x, String y)
  username = x;
  pass = y;

 public String getPass()
  return pass;

After creating the class in the project, we included the data in the class with the help of the constructor, then we created a getter and accessed the hidden data.

Leave a Reply

Your email address will not be published. Required fields are marked *