Class in Java

We are already aware of this primary concept that a Class in Java is a collection of similar objects grouped together.

Class can be theoretically defined as a collection of objects that contains related functions and member variables to operate on a set of data provided as input.

In Object Oriented Programming approach, there arises a need to hide the data items of an application and use only the essential feature. A simpler way of understanding is:

For example, we are using a smartphone, now there may be some hardware as well as software components of your device. The hardware includes the battery, processor, motherboard, screen, etc. whereas the software is the operating system that is installed in it. Now when we are using the smartphone, our motive gets focused only on the usage of the device and not on inner components or the length of the OS’s code. This technique is called Data Hiding. This same concept can be implemented using a class in Java.

Declaring a Class:

<Access Specifier> class <Class_Name>

E.g:  public class Apple

{

//body of class

}

Instance Variables:

Instance Variables or Global Variables or Member Variables are those variables that are freely accessible from anywhere within the class, i.e. they are globally accessible throughout the class.

Components of a Class:

External Wrapper is the class header that is where the class is declared along with the opening and closing braces. Internal Wrapper is defined as the inner body of the class that contains the instant or global variables, constructors and functions or methods.

Access Specifiers:

Access Specifiers are those keywords that are used to define the scope of a member method’s usage in a program.

They are:

  • Private: When a function is declared as private, they can be used only within their class.
  • Public:  When a function is declared as public, they can be used even outside the visibility of the class.
  • Protected: When a function is declared as Protected, they can be used within their class but can be inherited to another class.

New Keyword:

The new keyword is used to create an object which is used to invoke a function and is also used to declare an array. It is used to allocate memory while creating dimensional arrays.

This Keyword:

This keyword is used to refer to a current object or instance variable. It is also used to invoke the class constructor.

Class in Java