CodeBlanks Logo Icon CodeBlanks

class

Learn to define classes with class.

Defining a class

A class is a template used to create objects. In Java a class starts with the class keyword, followed by the class name and a body in curly braces.

Example: class User {}. Here User is the class name; the space between the braces is the body. The class name should start with an uppercase letter; for example User, Book, Order. Defining a class does not run it; it only prepares the template.

Body and fields

The class body is the area between the curly braces. You add fields and methods here. A field holds the class data; a method defines behavior.

Example: class Book { String title; }. Here title is a field of type String. Each field is declared with a type and a name, followed by a semicolon. The body can be empty but usually holds at least one field or method.

Practice Define the User class

Define a class named User. Add a String name field inside it. Write a main method; inside it create a User instance, assign a value to name and print it with System.out.println.

Starter code

Main.java
// Define the User class
// Add a String name field
// Instantiate and print in main

Sample solution

Main.java
class User {
    String name;
    public static void main(String[] args) {
        User u = new User();
        u.name = "Alex";
        System.out.println(u.name);
    }
}

Expected output

Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a valid Java class definition?

  • def User: pass
  • function User() { }
  • User class { }
  • class User { } Correct answer

Explanation: The class keyword, the class name and curly braces form the body.

2 Complete the class definition

Question
class User____
    String name;
}
Answer
class User{
    String name;
}

Explanation: The curly brace starts the body.

3 Match the parts of a class

Term Meaning
class Keyword
User Class name
{ } Body

All lessons in Intermediate