0
0
Javaprogramming~5 mins

Class definition in Java

Choose your learning style9 modes available
Introduction

A class is like a blueprint to create objects. It helps organize data and actions together.

When you want to group related data and actions about something, like a Car or a Book.
When you want to create many similar things with different details.
When you want to keep your program organized and easy to understand.
When you want to reuse code by creating objects from the same blueprint.
When you want to model real-world things in your program.
Syntax
Java
class ClassName {
    // fields (data)
    // methods (actions)
}

The class name should start with a capital letter.

Fields store information, methods define what the class can do.

Examples
This class defines a Dog with a name and age.
Java
class Dog {
    String name;
    int age;
}
This class defines a Car with a model and a method to start it.
Java
class Car {
    String model;
    void start() {
        System.out.println("Car started");
    }
}
Sample Program

This program defines a Person class with name and age. It has a method to say hello. In main, it creates a Person, sets details, and calls the method.

Java
public class Person {
    String name;
    int age;

    void sayHello() {
        System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
    }

    public static void main(String[] args) {
        Person p = new Person();
        p.name = "Alice";
        p.age = 30;
        p.sayHello();
    }
}
OutputSuccess
Important Notes

Remember to create objects from the class to use it.

Fields can be different types like int, String, etc.

Methods can use fields to do actions or show information.

Summary

A class is a blueprint to create objects with data and actions.

Use classes to organize and reuse code easily.

Define fields for data and methods for actions inside a class.