0
0
Javaprogramming~5 mins

Classes and objects in Java

Choose your learning style9 modes available
Introduction

Classes help you create blueprints for things. Objects are actual things made from these blueprints.

When you want to group related data and actions together, like a car with speed and drive methods.
When you want to create many similar things, like multiple users in an app.
When you want to organize your code to be easier to understand and reuse.
Syntax
Java
class ClassName {
    // fields (data)
    // methods (actions)
}

// Create an object
ClassName objectName = new ClassName();

Class names start with a capital letter by convention.

Objects are created using the new keyword.

Examples
This example shows a Dog class with name and age fields and a bark method. We create a Dog object and call bark.
Java
class Dog {
    String name;
    int age;

    void bark() {
        System.out.println(name + " says Woof!");
    }
}

Dog myDog = new Dog();
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark();
This example shows a Light class with a boolean field and a method to switch it on or off.
Java
class Light {
    boolean isOn;

    void toggle() {
        isOn = !isOn;
        System.out.println("Light is now " + (isOn ? "On" : "Off"));
    }
}

Light lamp = new Light();
lamp.toggle();
lamp.toggle();
Sample Program

This program defines a Car class with color and speed. It creates a Car object, sets its properties, and calls the drive method to print a message.

Java
class Car {
    String color;
    int speed;

    void drive() {
        System.out.println("The " + color + " car is driving at " + speed + " km/h.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.color = "red";
        myCar.speed = 50;
        myCar.drive();
    }
}
OutputSuccess
Important Notes

Fields store information about the object.

Methods define what the object can do.

You can create many objects from one class, each with its own data.

Summary

Classes are blueprints for objects.

Objects are instances of classes with their own data.

Use classes and objects to organize and reuse your code.