HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

Java create class – how to create objects?

By Lokesh Gupta | Filed Under: Java Basics

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

1. Class vs 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 an HR application, actors are employee, manager, department or reports. An object is an instance of a class.

The classes are the template that describes the state and behavior of its objects.

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
}

2.1. Types of classes

In Java, you can have two types of class.

  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 to create objects of a class. we must have at least one constructor for a class (if we do declare explicitly then JVM inject default constructor for we).

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:

public class Main 

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

Suppose every object of ‘Human’ class has two properties: a name and a gender. The human class should include declarations of two fields: one to represent name and one to represent 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.

3.2. Methods

A Java method is a collection of statements that are grouped together to perform an operation. Methods are generally used to modify the state of class fields. Methods also can be used to delegate the 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");
        }
}

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

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

4. How to create objects?

In Java, to create an object from a class, use new keyword along with one of it’s 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 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 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 null type. We cannot assign null to a primitive type variable, and that’s why 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 !!

Read More: Oracle Java Doc

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Ask Questions & Share Feedback Cancel reply

Your email address will not be published. Required fields are marked *

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

Java Tutorial

  • Java – Introduction
  • Java – JDK, JRE and JVM
  • Java – Naming Conventions
  • Java – ClassPath
  • Java – Variables
  • Java – Operators
  • Java – keywords
  • Java – Data Types
  • Java – Primitive Types
  • Java – Wrapper Classes
  • Java – Types of Statements
  • Java – Control Statements
  • Java – String
  • Java – Create Class
  • Java – main() Method
  • Java – Comments
  • Java – hashCode() and equals()
  • Java – System Properties
  • Java – Pass-by-Value
  • Java – 32-bit vs. 64-bit
  • Java – java.exe vs javaw.exe
  • Java – Generate Bytecode
  • Java – Little-Endian vs Big-Endian
  • Java – Command Line Args
  • Java – Compare floats
  • Java – Static Import
  • Java – Recursion
  • Wrapper Class Internal Caching

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Java Collections
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap