Skip to content
Justice Tech School

Classes and Objects

A class defines fields and methods. new creates an object. The constructor sets up fields.

Example
public class Main {
  static class Person {
    String name; int age;
    Person(String name, int age) { this.name = name; this.age = age; }
    String describe() { return name + " (" + age + ")"; }
  }
  public static void main(String[] args) {
    Person p = new Person("Ada", 30);
    System.out.println(p.describe());
  }
}

Result

Ada (30)

Exercise

Create an object.

Person p =  Person();

Quiz Test

What does a constructor do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.