Class (Java)

A class in Java is a blueprint for creating objects that groups together data (fields) and behavior (methods). Almost all Java code lives inside a class.

Java

A class describes what an object knows (its fields/variables) and what it can do (its methods). You create actual objects from a class using the new keyword.

By convention, class names use UpperCamelCase, and a public class must be saved in a file with the same name (for example, class Dog goes in Dog.java).

Examples

Java

public class Dog {
    String name;

    String speak() {
        return name + " says woof";
    }

    public static void main(String[] args) {
        Dog d = new Dog();
        d.name = "Rex";
        System.out.println(d.speak());
    }
}

Output:

Rex says woof

Learn it in a lesson

See also

Back to the Dictionary