Class
A class is the blueprint for creating objects, it defines the structure and behavior that objects will have.
Basic Structure
Section titled “Basic Structure”public class ClassName { // Fields (attributes) private int myField;
// Constructor public ClassName() { // Initialize fields }
// Methods public void myMethod() { // Method implementation }}Components
Section titled “Components”- Class Declaration: Starts with optional access modifier, followed by the keyword
classand the class name - Fields: Variables that belong to the class
- Constructors: Special methods used to initialize objects
- Methods: Functions that define the behavior of the class
Example
Section titled “Example”public class Person { // Fields private String name; private int age;
// Constructor public Person(String name, int age) { this.name = name; this.age = age; }
// Getter methods public String getName() { return name; }
public int getAge() { return age; }
// Method public void introduceYourself() { System.out.println("Hello, my name is " + name + " and I am " + age + " years old."); }}Constructors
Section titled “Constructors”A constructor is a special method in a class that is called when an object is created.
- It is used to initialize the object’s fields.
- Constructors have the same name as the class and do not have a return type.
public class Car { private String model;
// Constructor public Car(String model) { this.model = model; }
public void showInfo() { System.out.println("Model: " + model); }}
// Usage:Car car = new Car("Toyota");car.showInfo(); // Output: Model: ToyotaBest Practices
Section titled “Best Practices”- Class names should start with a capital letter
- Follow camelCase naming convention
- Keep classes focused on a single responsibility
- Properly encapsulate fields using private access and public getter/setter methods