CSDT BLOG

DISCOVER COLLECTIONS AND BLOGS THAT MATCH YOUR INTERESTS.




Share ⇓




Learn how to Create & Implement Objects and Classes in Java

Bookmark

Learn how to Create & Implement Objects and Classes in Java

Learn how to Create & Implement Objects and Classes in Java

Java is one of the most prominently used Object-oriented programming languages it becomes very necessary to know these concepts by heart. Thus, I bring you this article, where I will be giving you a complete overview of Java objects and classes.

Below are the topics covered in this article:

1. What is a Java Class?
2. How to Create a Class in Java?
3. Types of Classes in Java
4. What is an Object in Java?
5. How to Create a Java Object?

Classes and Objects in Java programming are two such concepts which go hand in hand. You can’t learn one without having the knowledge of the other. 

What is a Java Class?

A class in Java is a blueprint from which an object is created. It is a logical entity that helps in defining the behavior and properties of an object. A class can only be accessed from outside via its instance. Every class in Java must belong to some package. Packages in Java are nothing but a group of similar types of classes, interfaces, and sub–packages.

The classes in Java are generally classified under two categories:

1. Built-in Classes
Built-in classes in Java are the classes which come bundled within predefined packages in Java. Predefined packages are the packages which are developed by Sun MicroSystems and are provided as a part of JDK (Java Development Kit) to help out a java programmer. A few of the majorly used built-in classes are:

a) java.lang.String
b) java.lang.System
c) java.lang.Exception
d) java.lang.Object
e) java.lang.Class
f) java.util.Date
g) java.util.HashMap
h) java.util.ArrayList
i) java.util.Iterator
j) java.lang.Thread

2. User-Defined/ Custom Classes
As the name suggests, a custom or user-defined class is a class that is created by a user. It will contain the class members as defined by the user.

You will see how to create a class in the next section of this Java objects and classes article.

How to Create a Class in Java?
Creating a class is really simple in Java.

Below is a basic skeleton of a Java class:

<access specifier> class  <classname>
{
//classbody
}

In order to create a full-fledged custom class, you need to know what are the various elements a class is made up of.

A Java class generally consists of the following:

1. Fields
Fields of a class are used to define the properties or state attributes of the class objects. Thus they are declared within the body of the class. The general syntax to declare a class field is given below:

public class Student
{
    // A field declaration
    //<<modifiers>> <<data type>> <<field name>> = <<initial value>>;
    public int Roll = 1101;
 
}

2. Methods
A method in Java is a collection of a statement which determines the behavior of a class object. They are generally used to modify the state of a class field. By using methods you can also delegate tasks in other objects.

Below I have listed down a few properties of a method:

1. It can have zero or more arguments
2. A method must return void or least a single value
3. It can be overloaded i.e you can define more than one method with the same name but it must have different implementation
4. It can be overridden as well i.e you can define methods with the same name and syntax in parent and child classes.

Below is a simple example to define and invoke a method in a Java class:

public class Example{
    //Defining a no argument method
    public void show(){
        System.out.println(“Welcome to CSDT’s Tutorial”);
    }
 
    //Defining a two argument method
    public void add(int a, int b) {
        int sum = a+b;
        System.out.println(sum);
        }
 
    public static void main(String[] args) {
        //Initializing variables
        int var1 = 10;
        int var2 = 20;
 
        System.out.println(“CSDT Centre Objects and Classes in Java”);
 
        //Invoking methods
        show();
 
        System.out.println("Sum of given numbers is "+ add(var1,var2));
    }
}

3. Constructors
A constructor in Java is used to initialize an object of a class immediately after the object is created. A constructor must have its name same as its class. In Java, every class has a constructor known as the default constructor but you can add more according to your requirement.

Below is an example of the same:

public class Exam{
    public Exam() {
    //default constructor
    }
 
    public Exam(String name) {
    // This constructor has one parameter
    }
}

4. Blocks
A Block in Java is a group of one or more statements enclosed within braces. 

There are two types of blocks in Java:

1. Static Block
A static block in Java is the block which is executed only once at the time of class loading. A static block is also known as a static initialization block. A class can have more than one static blocks.  The general syntax for a Static Block declaration is:

public class Exam{
    static{
        //block body
    }
}

2. Instance Block
An instance block in Java is the block which is executed whenever an object is created. A static block is also known as instance initialization block. An instance block is executed in the order they are written after the constructor makes the call to super.  The general syntax for an Instance Block declaration is given below:

public class Exam{
    {
        //block body
    }
}

Rules to Create a Class

i) A Java class must have the class keyword followed by the class name, and class must be followed by a legal identifier.

ii) The class name must start with a capital letter and if you are using more than one word to define a class name, every first letter of the latter words should be made capital.

iii) There should not be any spaces or special characters used in a class name except the dollar symbol($) and underscore(_).

iv) A Java class can only have public or default access specifier.

v) It must have the class keyword, and class must be followed by a legal identifier.

vi) It can extend only one parent class. By default, all the classes extend java.lang.Object directly or indirectly.

vii) A class may optionally implement any number of interfaces separated by commas.

viii) The class’s members must be always declared within a set of curly braces {}.

ix) Each .java source file can contain any number of default classes but can only have one public class.

x) Class containing the main() method is known as the Main class as it will act as the entry point to your program. 

What is an Object in Java?
An object in Java is the real-world entity which has its own property and behavior. These are considered to be the fundamental concepts of Java and uses classes as their blueprints. A Java program can have as many objects as required. An object in Java typically insists of the following:

1. State: This is represented by the attributes and properties of an object.
2. Behavior: This is defined by the methods of an object
3. Identity: This provides a unique name to an object and also enables the communication between two or more objects.

Suppose we have an object called Mobile. It will have some identity like its model, attributes such as color, RAM, price, and behavior such as text, on, off, etc. All the instances of the class Mobile share the same set of attributes and the behavior. Here one thing you must remember is that attribute values of each object will be unique. Moreover, a single Java class can have any number of instances.

How to Create a Java Object?

public class Exam{
    public Exam() {
        // Default Constructor
        System.out.println(“This is a default constructor” );
    }
    public Exam(String name) {
        // This constructor has one parameter
        System.out.println(“Hello: ” + name );
        System.out.println(“Welcome to CSDT’s Tutorial”);
   }
 
   public static void main(String []args) {
    //Creating an object using default constructor
    Exam myObj = new Exam();
 
    //Creating an object using parameterized constructor
    Exam myObj = new Exam( “Max” );
   }
 }


Please visit for more information www.csdt.co.in

11

Our Recent Coment
Priyanka kasyap

I told, this is the best article regarding class and objects as well as some important topics related Class and object in Java programming language.. Thank you for submitting this article..