Java

Explain How to Create and Use Classes and Objects in Java with Examples

By Utility Zone · 2025-11-06T09:39:12.333624

Java is an object-oriented programming language where everything is organized around classes and objects. A class is a blueprint or template that defines the structure and behavior of objects, while an object is a specific instance of a class. Understanding how to create and use classes and objects is fundamental to Java development.12

Relationship between Java classes (blueprints) and objects (instances)

Relationship between Java classes (blueprints) and objects (instances)


Understanding Classes and Objects

Class: A template that defines what data (attributes) and actions (methods) objects of that type will have.12

Object: An instance of a class created using the new keyword, representing a real-world entity with specific values for the attributes defined in the class.21

Real-World Analogy

Think of a class as a cookie cutter and objects as individual cookies made from that template. All cookies have the same shape and structure (from the class), but each cookie is a separate, unique item with its own characteristics.12


Class Declaration Syntax

The basic structure of a Java class includes:34

[access_modifier] class ClassName {
    // Instance variables (fields/attributes)
    dataType variableName;
    
    // Constructor(s)
    ClassName() {
        // Constructor code
    }
    
    // Methods
    return_type methodName(parameters) {
        // Method code
    }
}

Components of a Class

1. Access Modifier (optional)

  • public: Class is accessible from anywhere
  • default (no modifier): Accessible only within the package

2. Class Keyword

  • Declares that this is a class

3. Class Name

  • By convention, starts with a capital letter (e.g., Student, Car, Person)

4. Instance Variables

  • Attributes that store data for each object56
  • Each object has its own copy of instance variables
  • Can have different values for different objects

5. Constructor

  • Special method that initializes objects when they are created789
  • Has the same name as the class
  • No return type (not even void)

6. Methods

  • Define the behavior of objects10
  • Can manipulate instance variables

Creating Objects Using the new Keyword

Objects are created using the new keyword, which performs three operations:1112813

Syntax:1311

ClassName objectName = new ClassName(parameters);

Process:813

  1. Declaration: A reference variable with the object type is created
  2. Instantiation: The new keyword allocates memory on the heap for the object
  3. Initialization: The constructor is called to initialize the object with the provided parameters

Example:1213

// Creating objects of the Student class
Student student1 = new Student("Alice", 20);  // Using parameterized constructor
Student student2 = new Student();              // Using default constructor

Constructors

Constructors are special methods that initialize objects when they are created.789

Key Characteristics of Constructors:97

  • Same name as the class
  • No return type (not even void)
  • Automatically called when an object is created with the new keyword
  • Can accept parameters to initialize object attributes with specific values
  • Set initial state of an object to ensure it's valid from the beginning

Default Constructor

If you don't define a constructor, Java automatically provides a default (no-argument) constructor that initializes all instance variables with their default values.78

Example:7

public class Car {
    String model;
    int year;
    
    // If no constructor is defined, Java creates a default one:
    // public Car() { }
    
    public static void main(String[] args) {
        Car myCar = new Car();  // Uses default constructor
    }
}

Parameterized Constructor

A parameterized constructor accepts arguments to initialize instance variables with specific values.78

Example:7

public class Car {
    String model;
    int year;
    
    // Parameterized constructor
    public Car(String model, int year) {
        this.model = model;
        this.year = year;
    }
    
    public static void main(String[] args) {
        Car myCar = new Car("Toyota", 2020);
        System.out.println(myCar.model);  // Output: Toyota
        System.out.println(myCar.year);   // Output: 2020
    }
}

Instance Variables

Instance variables store the state (data) of an object.56

Characteristics of Instance Variables:65

  • Declared in the class body, typically before methods
  • Unique for each object: Each object has its own copy with potentially different values
  • Created in heap memory when an object is instantiated
  • Lifetime: Exist as long as the object exists
  • Access modifiers can control visibility: public, private, protected, or package-private5

Example:5

public class Student {
    // Instance variables
    private String name;
    private int age;
    private double gpa;
    
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Alice";
        s1.age = 20;
        
        Student s2 = new Student();
        s2.name = "Bob";
        s2.age = 21;
        
        // Each object has its own copy of instance variables
        System.out.println(s1.name);  // Output: Alice
        System.out.println(s2.name);  // Output: Bob
    }
}

Instance Methods

Instance methods define the behavior of objects and can access and modify instance variables.10

Syntax:10

[access_modifier] return_type methodName(parameters) {
    // Method body
}

Characteristics:10

  • Belong to objects (not to the class)
  • Must create an object to call an instance method
  • Can access and modify instance variables
  • Can call other instance or static methods
  • Cannot exist independently without an object

Example:10

public class Student {
    String name;
    int age;
    
    // Instance method
    void displayInfo() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
    
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Alice";
        s1.age = 20;
        
        // Call instance method on the object
        s1.displayInfo();  // Output: Name: Alice, Age: 20
    }
}

The this Keyword

The this keyword is a reference variable that refers to the current object.141516

Uses of this:151614

1. Refer to Instance Variables (most common use)

  • Differentiates between instance variables and parameters with the same name1516
public class Person {
    int age;
    
    public Person(int age) {
        this.age = age;  // this.age refers to instance variable
                         // age refers to parameter
    }
    
    public static void main(String[] args) {
        Person p = new Person(25);
        System.out.println(p.age);  // Output: 25
    }
}

Without this, the code would be age = age; which assigns the parameter to itself, leaving the instance variable uninitialized.16

2. Invoke Current Class Methods:14

public class Example {
    void method1() {
        System.out.println("Method 1");
    }
    
    void method2() {
        this.method1();  // Call another instance method
    }
}

3. Invoke Current Class Constructor (Constructor Chaining):14

public class Box {
    int length, width, height;
    
    Box() {
        this(1, 1, 1);  // Call parameterized constructor
    }
    
    Box(int l, int w, int h) {
        length = l;
        width = w;
        height = h;
    }
}

Constructor Overloading

Constructor overloading allows a class to have multiple constructors with different parameter lists.1718

Why Use Constructor Overloading?:1817

  • Initialize objects in different ways
  • Set sensible defaults when property values are unknown
  • Provide flexibility in object creation
  • Support backward compatibility with new properties
  • Improve code reusability

Rules for Overloading Constructors:17

  • Constructors must have the same name (which is the class name)
  • Constructors must have different parameter lists (different number or type of parameters)
  • The order of parameters matters

Example:1718

public class Point {
    int x;
    int y;
    
    // Default constructor - creates point at origin (0, 0)
    Point() {
        x = 0;
        y = 0;
    }
    
    // Constructor with two parameters
    Point(int a, int b) {
        x = a;
        y = b;
    }
    
    // Constructor with one parameter - creates a point where x = y
    Point(int a) {
        x = a;
        y = a;
    }
    
    public static void main(String[] args) {
        Point p1 = new Point();        // Uses default constructor (0, 0)
        Point p2 = new Point(4, 2);    // Uses two-parameter constructor (4, 2)
        Point p3 = new Point(5);       // Uses one-parameter constructor (5, 5)
        
        System.out.println("p1: (" + p1.x + ", " + p1.y + ")");
        System.out.println("p2: (" + p2.x + ", " + p2.y + ")");
        System.out.println("p3: (" + p3.x + ", " + p3.y + ")");
    }
}

Output:

p1: (0, 0)
p2: (4, 2)
p3: (5, 5)

Method Overloading

Similar to constructors, methods can also be overloaded with the same name but different parameters.19

Example:19

public class Calculator {
    // Method 1: Add two integers
    void sum(int a, int b) {
        System.out.println("Sum of integers: " + (a + b));
    }
    
    // Method 2: Add two doubles
    void sum(double a, double b) {
        System.out.println("Sum of doubles: " + (a + b));
    }
    
    // Method 3: Add three integers
    void sum(int a, int b, int c) {
        System.out.println("Sum of three integers: " + (a + b + c));
    }
    
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        calc.sum(5, 10);              // Calls Method 1
        calc.sum(5.5, 10.5);          // Calls Method 2
        calc.sum(5, 10, 15);          // Calls Method 3
    }
}

Output:

Sum of integers: 15
Sum of doubles: 16.0
Sum of three integers: 30

Complete Example: Bank Account Class

Here's a comprehensive example demonstrating all the concepts discussed:2

public class BankAccount {
    // Instance variables
    private String accountHolder;
    private double balance;
    private String accountNumber;
    
    // Default constructor
    public BankAccount() {
        accountHolder = "Unknown";
        balance = 0.0;
        accountNumber = "0000000000";
    }
    
    // Parameterized constructor
    public BankAccount(String name, double initialBalance, String accNum) {
        this.accountHolder = name;
        this.balance = initialBalance;
        this.accountNumber = accNum;
    }
    
    // Instance method: Deposit money
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: 
quot; + amount); } else { System.out.println("Invalid deposit amount"); } } // Instance method: Withdraw money public void withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; System.out.println("Withdrawn:
quot; + amount); } else { System.out.println("Invalid withdrawal amount or insufficient balance"); } } // Instance method: Check balance public void checkBalance() { System.out.println("Account Holder: " + accountHolder); System.out.println("Account Number: " + accountNumber); System.out.println("Current Balance:
quot; + balance); } public static void main(String[] args) { // Create objects BankAccount acc1 = new BankAccount("Alice", 5000, "ACC001"); BankAccount acc2 = new BankAccount("Bob", 3000, "ACC002"); // Use instance methods System.out.println("=== Account 1 ==="); acc1.checkBalance(); acc1.deposit(1000); acc1.withdraw(500); acc1.checkBalance(); System.out.println("\n=== Account 2 ==="); acc2.checkBalance(); acc2.deposit(2000); acc2.withdraw(1500); acc2.checkBalance(); } }

Output:

=== Account 1 ===
Account Holder: Alice
Account Number: ACC001
Current Balance: $5000.0
Deposited: $1000
Withdrawn: $500
Account Holder: Alice
Account Number: ACC001
Current Balance: $5500.0

=== Account 2 ===
Account Holder: Bob
Account Number: ACC002
Current Balance: $3000.0
Deposited: $2000
Withdrawn: $1500
Account Holder: Bob
Account Number: ACC002
Current Balance: $3500.0

Key Differences: Classes vs Objects

AspectClassObject
TypeLogical entity (Template)Physical entity (Instance)
DeclarationDefined onceMultiple objects can be created
MemoryNo memory allocatedMemory allocated when created with new
LifetimeExists in source codeExists at runtime
PurposeBlueprint defining structure and behaviorRepresents actual data with specific values

Best Practices

  1. Use meaningful class names that clearly describe what the class represents
  2. Encapsulate data by making instance variables private and providing methods to access them
  3. Initialize variables properly in constructors to ensure objects are always in a valid state
  4. Use constructor overloading to provide flexible ways of creating objects
  5. Follow naming conventions: Classes start with capital letters, methods and variables start with lowercase
  6. Use the this keyword to improve code clarity when differentiating between instance variables and parameters
  7. Document your classes with comments explaining their purpose and usage

Understanding classes and objects is essential for writing organized, maintainable, and scalable Java applications.31 <span style="display:none">20</span>


<div align="center">⁂</div>

Footnotes

  1. https://www.geeksforgeeks.org/java/classes-objects-java/ ↩ ↩2 ↩3 ↩4 ↩5

  2. https://www.tutorialspoint.com/java/java_object_classes.htm ↩ ↩2 ↩3 ↩4 ↩5

  3. https://www.cs.princeton.edu/courses/archive/spr96/cs333/java/tutorial/java/javaOO/classdecl.html ↩ ↩2

  4. https://syntaxdb.com/ref/java/class-declare ↩

  5. https://www.carmatec.com/blog/java-instance-variables-guide-with-examples/ ↩ ↩2 ↩3 ↩4 ↩5

  6. https://www.scaler.com/topics/instance-variable-in-java/ ↩ ↩2 ↩3

  7. https://www.w3schools.com/java/java_constructors.asp ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7

  8. https://www.simplilearn.com/tutorials/java-tutorial/constructor-in-java ↩ ↩2 ↩3 ↩4 ↩5 ↩6

  9. https://www.digitalocean.com/community/tutorials/constructor-in-java ↩ ↩2 ↩3

  10. https://www.geeksforgeeks.org/java/instance-methods-in-java/ ↩ ↩2 ↩3 ↩4 ↩5

  11. https://www.datacamp.com/doc/java/new ↩ ↩2

  12. https://www.geeksforgeeks.org/java/different-ways-create-objects-java/ ↩ ↩2

  13. https://www.ccbp.in/blog/articles/new-keyword-in-java ↩ ↩2 ↩3 ↩4

  14. https://www.datacamp.com/doc/java/this ↩ ↩2 ↩3 ↩4

  15. https://www.w3schools.com/java/ref_keyword_this.asp ↩ ↩2 ↩3

  16. https://www.w3schools.com/java/java_this.asp ↩ ↩2 ↩3 ↩4

  17. https://www.geeksforgeeks.org/java/constructor-overloading-java/ ↩ ↩2 ↩3 ↩4

  18. https://www.theserverside.com/video/Constructor-overloading-in-Java ↩ ↩2 ↩3

  19. https://www.startertutorials.com/corejava/java-overloading.html ↩ ↩2

  20. https://www.edureka.co/blog/instance-variable-in-java/ ↩