Java class


A class is a template for creating different objects/instances which defines its properties and behaviour. In other words, a class is a collection of objects which have common properties.

A class is only a logical entity so it doesn’t occupy any space in memory.

Syntax:

class <class_name>
{
    fields;  
    methods;  
}

Fields: It is a variable inside a class.

Methods: It is like a function that is used to expose the behaviour of an object.

Note: Java fields and methods are case sensitive.


Example:

class Student
{
    int rollno;     // field
    String name;    // field

    // method
    void insertRecord(int r, String n)
    {
        rollno = r;
        name = n;
    }

    // method
    void displayInformation()
    {
        System.out.println(rollno + " " + name);
    }
}

// main class
class StudentData
{
    public static void main(String args[])
    {
        Student s1 = new Student();  
        s1.insertRecord(107, "TutorialsDuniya");  
  		s1.displayInformation();  
    }
}

A class can have multiple types of variables:

  1. Local variables: These variables are defined inside methods, constructors or blocks. These variables will be declared and initialized within the method and will be destroyed when the method has terminated.
  2. Instance variables: These variables are defined within a class but outside any method. These variables doesn't get any memory at compile time but gets memory at run time when object (instance) is created. We can access these variables from inside any method, constructor or blocks of the class.
  3. class variables: These variables are declared within a class but outside any method with the static keyword.