Open In App

Classes and Objects in Java

Last Updated : 12 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior. For example, the animal type Dog is a class while a particular dog named Tommy is an object of the Dog class.

In this article, we will discuss Java objects and classes and how to implement them in our program.

Java Classes

A class in Java is a set of objects which shares common characteristics/ behavior and common properties/ attributes. It is a user-defined blueprint or prototype from which objects are created. For example, Student is a class while a particular student named Ravi is an object.

Properties of Java Classes

  1. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.
  2. Class does not occupy memory.
  3. Class is a group of variables of different data types and a group of methods.
  4. A Class in Java can contain:
    • Data member
    • Method
    • Constructor
    • Nested Class
    • Interface

If you’re looking to gain a deeper understanding of Java and its object-oriented principles, exploring a comprehensive Java Programming Online course can be a valuable step. It will help you master the core concepts of classes and objects, and how to effectively use them in building robust Java applications.

Class Declaration in Java

access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface;
}

Example of Java Class

Java
// Java Program for class example

class Student {
    // data member (also instance variable)
    int id;
    // data member (also instance variable)
    String name;

    public static void main(String args[])
    {
        // creating an object of
        // Student
        Student s1 = new Student();
        System.out.println(s1.id);
        System.out.println(s1.name);
    }
}
Java
// Java program to Illustrate Creation of Object
// Using new Instance

// Main class
class GFG {

    // Declaring and initializing string
    String name = "GeeksForGeeks";

    // Main driver method
    public static void main(String[] args)
    {
        // Try block to check for exceptions
        try {
            Class cls = Class.forName("GFG");
            // Creating object of main class
            // using instance method
            GFG obj = (GFG)cls.newInstance();
            // Print and display