Create class and object in java

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.

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

  • A class declaration may have zero or more modifiers.
  • The keyword class is used to declare a class.
  • The > 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.

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.
Читайте также:  Json rpc example java

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.

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:

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.

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.

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.

  • 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

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:

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

  • 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(); >>
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(); >>
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.

> > = new >; //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.

Источник

Java Classes and Objects

Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.

A Class is like an object constructor, or a «blueprint» for creating objects.

Create a Class

To create a class, use the keyword class :

Main.java

Create a class named » Main » with a variable x:

Remember from the Java Syntax chapter that a class should always start with an uppercase first letter, and that the name of the java file should match the class name.

Create an Object

In Java, an object is created from a class. We have already created the class named Main , so now we can use this to create objects.

To create an object of Main , specify the class name, followed by the object name, and use the keyword new :

Example

Create an object called » myObj » and print the value of x:

Multiple Objects

You can create multiple objects of one class:

Example

Create two objects of Main :

Using Multiple Classes

You can also create an object of a class and access it in another class. This is often used for better organization of classes (one class has all the attributes and methods, while the other class holds the main() method (code to be executed)).

Remember that the name of the java file should match the class name. In this example, we have created two files in the same directory/folder:

Main.java

Second.java

When both files have been compiled:

You will learn much more about classes and objects in the next chapters.

Источник

Оцените статью