Skip to content

Class

This content is for Java. Switch to the latest version for up-to-date documentation.

A class is the blueprint for creating objects, it defines the structure and behavior that objects will have.

public class ClassName {
// Fields (attributes)
private int myField;
// Constructor
public ClassName() {
// Initialize fields
}
// Methods
public void myMethod() {
// Method implementation
}
}
  1. Class Declaration: Starts with optional access modifier, followed by the keyword class and the class name
  2. Fields: Variables that belong to the class
  3. Constructors: Special methods used to initialize objects
  4. Methods: Functions that define the behavior of the class
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.");
}
}

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: Toyota
  • 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
Built with passion by Ngineer Lab