An overview of class and object in Java

As we know that Java is an object-oriented programming language. It is allied with classes and objects together with its attributes and methods.

For example: in real life, a Perfume is an object. The Perfume has attributes, such as smell and color, and methods, such as cold-extraction and Distillation.

The class works as a blueprint for making an object constructor.

Create a Class
To build a class, use the keyword class:
A class describes all the parameters that define an object.

Test.java
//Create a class named "Test" with a variable x:

public class Test {
  int x = 7;
}

The following are the access specifier

Public: Public classes, methods, and fields can be captured from everywhere. the only restriction is that a file with java source code can only include one public class whose name must also match the filename.

Default: If you do not set access to a specific level, then such a class, method, or fields will be available from inside the same package to which the class, methods, or fields reside but not from outside this package.

Protected: Protected methods and fields can only be captured within the same class with which the methods and fields are affiliated, within its subclasses, and within classes of the same package,

You use the protected access level when it is suitable for a class’s subclasses to have a connection to the methods or fields, but not for unrelated classes.

Private: Private methods are secure methods and fields can only be accessed within the same class to which the methods and fields belong.

Create an Object
In Java, an object originated from a class. Earlier we created the class named Test, so now we can use this to create objects.
To create an object of Test, define the class name, followed by the object name, and use the keyword new:

Example
Create an object called "myObject" and print the value of x:

public class Test {
  int x = 7;

  public static void main(String[] args) {
    Test myObject = new Test();
    System.out.println(myObject.x);
  }
}

 

Keywords: