Java Class and Object

Classes are the basic units of programming in the object-oriented programming. In this Java tutorial, learn to write classes and how to create new objects of a class in Java.

1. Difference between a Class and an Object

In Java, objects are containers like data structures that have state and behavior. Ideally, objects represent the actors in the system or the application.

For example, in a Human Resource application, the main actors are Employee, Manager, Department, Report, etc.

The classes are the template that describes the state and behavior of its objects. A class can be used to create multiple objects. which are similar in structure but can have different states.

An object is an instance of a class.

2. How to Create a Class?

2.1. Syntax

The general syntax for declaring a class in Java is as follows:

<<modifiers>> class <<class name>> {
 
        // fields and members of the class
}
  • A class declaration may have zero or more modifiers.
  • The keyword class is used to declare a class.
  • The <<class name>> is a user-defined name of the class, which should be a valid identifier.
  • Each class has a body, which is specified inside a pair of braces ({ … }).
  • The body of a class contains its different components, for example, fields, methods, etc.

For example,

public class Main {

	// Empty body for now
}

2.2. Types of Classes

In Java, we can have two types of classes:

  1. Abstract class – These classes are abstract. These are incomplete classes. It means you cannot create an instance of this class. You can only extend these classes to complete their specification.
  2. Non-abstract class – These classes define their full state and behavior. They are complete classes. You can create objects of this class.

3. Components of a Java Class

In Java, classes are used as templates to create objects. A class in Java may consist of five primary components. i.e.

Fields and methods are also known as class members. Constructors and both initializers are used during the initialization of the class i.e. creating objects using the class template.

Constructors are used for creating objects of a class. We must have at least one constructor for a class (if we don’t declare explicitly then JVM injects the default constructor for us).

Initializers are used to initialize fields of a class. We can have zero or more initializers of static or instance types.

3.1. Fields

Fields of a class represent properties (also called state attributes) of objects of that class. The fields are declared inside the body of the class. The general syntax to declare a field in a class is:

<<modifiers>> <<data type>> <<field name>> = <<initial value>>;

Suppose every object of the ‘Human‘ class has two properties: name and gender. The Human class should include declarations of two fields: one to represent the name and one to express gender.

public class Human {

        private String name;
        private String gender;
}

Here the Human class declares two fields: name and gender. Both fields are of the String type. Every instance (or object) of the Human class will have a copy of these two fields.

3.2. Methods or Functions

A Java method is a collection of statements that are grouped together to operate. Methods are generally used to modify the state of class fields. Methods also can be used to delegate tasks by calling methods in other objects.

In Java, methods may –

  • accept zero or more arguments
  • return void or a single value
  • be overloaded – means we can define more than one method with the same name but different syntax
  • be overridden – means we can define methods with the same syntax in parent and child classes
public class Human {

        private String name;
        private String gender;

        public void eat() {

        	System.out.println("I am eating");
        }
}

3.3. Constructors

A constructor is a named block of code that is used to initialize an object of a class immediately after the object is created. The general syntax for a constructor declaration is:

<<Modifiers>> <<Constructor Name>>(<<parameters list>>) throws <<Exceptions list>> {
 
        // Body of constructor goes here
}
  • A constructor can have its access modifier as public, private, protected, or default (no modifier).
  • The constructor name is the same as the simple name of the class.
  • The constructor name is followed by a pair of opening and closing parentheses, which may include parameters.
  • Optionally, the closing parenthesis may be followed by the keyword throws, which in turn is followed by a comma-separated list of exceptions.
  • Unlike a method, a constructor does not have a return type.
  • We cannot even specify void as a return type for a constructor. If there is any return type, then it is a method.
  • Remember that if the name of a construct is the same as the simple name of the class, it could be a method or a constructor. If it specifies a return type, it is a method. If it does not specify a return type, it is a constructor.

3.4. Instance Initialization Block

We saw that a constructor is used to initialize an instance of a class. An instance initialization block, also called instance initializer, is also used to initialize objects of a class.

An instance initializer is simply a block of code inside the body of a class, but outside of any methods or constructors. An instance initializer does not have a name. Its code is simply placed inside an opening brace and a closing brace.

Note that an instance initializer is executed in the instance context, and the keyword this is available inside the instance initializer.

public class Main
{
	{
		//instance initializer block
	}
}
  • we can have multiple instance initializers for a class.
  • All initializers are executed automatically in textual order for every object we create.
  • Code for all instance initializers is executed before any constructor.
  • An instance initializer cannot have a return statement.
  • It cannot throw checked exceptions unless all declared constructors list those checked exceptions in their throws clause.
public class Main {

    //instance initializer
    {
        System.out.println("Inside instance initializer");
    }

    //constructor
    public Main()
    {
        System.out.println("Inside constructor");
    }

    public static void main(String[] args) {
        new Main();
    }
}

Program output:

Inside instance initializer
Inside constructor

3.5. Static Initialization Block

  • A static initialization block is also known as a static initializer.
  • It is similar to an instance initialization block except it is used to initialize a class.
  • An instance initializer is executed once per object whereas a static initializer is executed only once for a class when the class definition is loaded into JVM.
  • To differentiate it from an instance initializer, we need to use the static keyword in the beginning of its declaration.
  • we can have multiple static initializers in a class.
  • All static initializers are executed in the textual order in which they appear and execute before any instance initializers.

A static initializer cannot throw checked exceptions. It cannot have a return statement.

public class Main {

    //static initializer
    static {
        System.out.println("Inside static initializer");
    }

    //constructor
    public Main()
    {
        System.out.println("Inside constructor");
    }

    public static void main(String[] args) {
        new Main();
    }
}

The program output:

Inside static initializer
Inside constructor

4. How to Create a New Object

In Java, to create an object from a class, use new keyword along with one of its constructors.

<<Class>> <<variable>> = new <<Call to Class Constructor>>;
 
//e.g.
 
Human human = new Human();

Remember, when we do not add a constructor to a class, the Java compiler adds one for us. The constructor that is added by the Java compiler is called a default constructor. The default constructor accepts no arguments. The name of the constructor of a class is the same as the class name.

The new operator is followed by a call to the constructor of the class whose instance is being created. The new operator creates an instance of a class by allocating the memory in a heap.

5. The ‘null’ Reference Type

Java has a special reference type called null type. It has no name. Therefore, we cannot define a variable of the null reference type. The null reference type has only one value defined by Java, which is the null literal. It is simply null.

The null reference type is assignment compatible with any other reference type. That is, we can assign a null value to a variable of any reference type. Practically, a null value stored in a reference type variable means that the reference variable is referring to no object.

// Assign the null value to john
 
Human john = null;    // john is not referring to any object
john = new Human();   // Now, john is referring to a valid Human object

Note that null is a literal of the null type. We cannot assign null to a primitive type variable, and that’s why the Java compiler does not allow us to compare a primitive value to a null value.

That’s all for this very basic tutorial about creating classes in java.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode