Class and Object In Java Programming

One of the most important features of the Java programming language is classes and objects. You can learn them exactly, it will be very useful for your application development.

What is Class?

Classes are used within classes of objects that can be considered as generic carriers. It can be similar to the general grading system we use in real life, for example, while the car is a class, the Toyota model is an object.

What is an Object?

Objects, on the other hand, are ready-to-use parts derived from classes. Instead of using classes within the project, we use derived objects. After the objects are created, all functions and variables are called from the object.

How to Create Class?

There are two ways to create a class in Java. The first is to create a class in a different file and the second method is to create a class other than the main in the same file. In this lesson, we will create it in a different file.

public class FileName
{
   // Code
}
How to Create Object?

To create an object, switch to a file containing the main function, then create your object by specifying your Class. After the object is created, you can find every function and variable you created as an Object.Name

FileName ObjectName = new FileName();
Example Class and Object

The main issue in this example is to create a product promotion profile and create a purchasing function to enable the product to be purchased. First, we will create a class and then manage the project with the object.

public static class ProductManager
{
   String ProductName;
   int Price;

   public void Buy()
   {
      System.out.println("Sold: " + ProductName);
   }
}

Let’s give the values of the variables in the class and create an object, then use the buy function in the object.

ProductManager productManager = new ProductManager();
productManager.ProductName = "Toyota";
productManager.Price = 35000;
productManager.Buy();
Output: 
Sold: 35000

Leave a Reply

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