Java Classes and Objects

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

1. Difference between a Class and an Object

In Java, objects are containers like data structure which have state and behavior. Objects represent the actors in the system or the application.

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

An object is an instance of a class.

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.

2. How to declare a Class

The general syntax for declaring a class in Java is:

<<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; Write we own
}

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. Ingradiants of Java Classes

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

  1. Fields
  2. Methods
  3. Constructors
  4. Static initializers
  5. Instance initializers

Fields and methods are also known as class members. Constructors and both initializers are used to during initialization of class i.e. creating objects using 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 inject 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.

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:

public class Main 

        // A field declaration
        <<modifiers>> <<data type>> <<field name>> = <<initial value>>;
}

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

public class Human {

        String name;
        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.

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 same name but different syntax
  • be overrided – means we can define methods with same syntax in parent and child classes
public class Human {

        String name;
        String gender;

        public void eat() {

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

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 package-level (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.

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 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 are 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();
    }
}

Output:

Inside instance initializer
Inside constructor

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 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();
    }
}

Output:

Inside static initializer
Inside constructor

How to Create Java Objects

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.

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 !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.