Java Classes


The class is in the main part of Java. It is the logical construction that the whole Java language is built on because it determines the size and nature of an object. For example, classes form the basis of object-oriented programming in Java. The concept you want to apply in Java must be within a class.


Class Fundamentals

The most important thing to understand about a class is that it defines a new data type. Once defined, this new type can be used to create that type of object. Thus, a class is a template for an object and an object is the instance of a class. Since an object has a class instance, you will often see two-word objects and instances and interchangeable.


The General Form of a Class

When you define a class, you declare its exact form and nature. You do this by specifying the data you have in it and the code that manages that data. Although very common classes may contain only code or data only, most real-world classes contain both. A class code defines the interface in its data as you can see.

A class is declared using class keywords. The classes used so far are very limited examples of its complete form. Classes can be more complicated. A simplified form of the class definition is shown here:

Program
class className
{
 type instance_Variable1;
 type instance_Variable2;
 //...
 type instance_VariableN;
 type methodName1(parameter-list)
 {
  //body of the method
 }
 type methodName2(parameter-list)
 {
  //body of the method
 }
 //...
 type methodNameN(parameter-list)
 {
  //body of the method
 }
}

A Simple Class

The class is shown below with a simple example. Here is a class called Rect that defines two instance variables: length, width. Currently, Rect does not contain any methods.

Program
class Rect
{
 double _length;
 double _width;
}

As mentioned, a class defines a new type of data. In this case, the new data type is called Rect. You will use this name to declare rectifier objects. It is important to remember that class announcements only create a template; It does not create an actual object. Thus, the previous code does not allow any Rect type object to exist.

To create an object of Rect class, see the following code:

Rect obj = new Rect(); // create a Rect object called obj

If you want to know about the object, you can see it given in the next tutorial.