Flat Preloader Icon

What Is Java Object And Classes

In Java, objects and classes are fundamental concepts in object-oriented programming (OOP). Let’s break down each concept:

Overview

  • What is Java Object and Classes? Encapsulation and Access Control
  • The this Keyword
  • Static Members
  • Method Overloading
  • By Value or By Reference
  • Loading, Linking and Initialization
  • Comparing Objects
  • The Garbage Collector

What Is Java Object & Classes?

  • What is Java Object?
  • Creating Object
  • Java Classes
    • Fields
    • Methods
    • The Method Main
    • Constructors

Class

  • A class in Java is a blueprint or a template for creating objects. Encapsulation and Access Control
  • It defines the properties (fields) and behaviors (methods) that objects of that class will have.
Here’s an example of a simple Java class:
				
					public class Car 
{
    // Fields (properties)
    String make;
    String model;
    int year;

    // Constructor
    public Car(String make, String model,
    int year)
    {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    // Method
    public void startEngine()
    {
        
    System.out.println
    ("The " + year 
    + " " + make + 
    " " + model + 
    " engine is running.");
    }
}

				
			

Object

  • An object is an instance of a class. It is a concrete realization of the class blueprint.
  • Objects are created from classes using the new keyword and a constructor of the class.
  • Each object has its own set of field values, independent of other objects created from the same class.
  • You can call the methods of an object to perform actions or interact with its data.
  • Here’s how you create and use objects based on the Car class:
				
					public class Main {
    public static void main(String[] args) 
    {
        // Creating objects
        Car car1 = new Car
        ("Toyota", "Camry", 2022);
        Car car2 = new Car
        ("Honda", "Civic", 2023);

        // Using objects
        car1.startEngine();
        
        car2.startEngine();
        
    }
}

				
			
In this example, car1 and car2 are objects created from the Car class. They have their own unique values for make, model, and year.