What a Java class is and how to write one

A class in Java is a blueprint for creating objects — it defines what data an object holds and what actions it can perform. When you write a class, you are describing a type of thing: a Person, a Car, a BankAccount. Later, you create individual objects from that blueprint.

The basic structure is straightforward: you write the word class, give it a name, open curly braces, and inside them put the data fields and methods that belong to that class. Java requires the class name to match the filename, and the file must end in .java.

Here is the simplest possible class:

public class Dog {   String name;   int age; }

This class called Dog has two pieces of data: a name (text) and an age (a number). You can now create Dog objects and give each one its own name and age.

Key Takeaways

  • A class starts with public class ClassName, must be saved in a file named ClassName.java, and contains fields (data) and methods (actions).
  • Fields are declared inside the class body with a type and a name, like String name; or int age;
  • A constructor is a special method that runs when you create a new object, and it usually sets the initial values of the fields.
  • Methods are actions the object can perform, written as public void methodName() { } or with a return type like public String getName() { }
  • You create an object from a class by writing Dog myDog = new Dog();, which calls the constructor and gives you an object to work with.

Fields: storing data in a class

Fields are variables that belong to the class. Each object created from the class gets its own copy of those fields. You declare a field by writing the data type, then the name, then a semicolon.

Common data types are String (text), int (whole numbers), double (decimal numbers), and boolean (true or false). You can declare as many fields as you need:

public class Car {   String color;   String brand;   int year;   double price;   boolean isRunning; }

Each Car object will have its own color, brand, year, price, and running status. When you create two Car objects, one can be red and the other blue — the fields are separate for each object.

Constructors: setting up a new object

A constructor is a method that runs automatically when you create a new object. It usually sets the starting values of the fields. The constructor has the same name as the class and no return type.

Here is a Dog class with a constructor:

public class Dog {   String name;   int age;   public Dog(String dogName, int dogAge) {     name = dogName;     age = dogAge;   } }

The constructor takes two pieces of information (called parameters): a name and an age. When you create a Dog, you pass those values in: Dog myDog = new Dog("Buddy", 3); The constructor then sets the name field to "Buddy" and the age field to 3.

If you do not write a constructor, Java provides an empty one automatically. But writing your own constructor lets you control what happens when an object is created.

Methods: actions an object can perform

A method is an action or behavior that an object can do. Methods are written inside the class, after the fields. Each method has a return type (what it gives back), a name, parentheses for parameters, and a body in curly braces.

Here is a Dog class with two methods:

public class Dog {   String name;   int age;   public Dog(String dogName, int dogAge) {     name = dogName;     age = dogAge;   }   public void bark() {     System.out.println(name + " says woof!");   }   public String getName() {     return name;   } }

The bark() method has return type void, which means it does not return anything — it just prints a message. The getName() method has return type String, which means it gives back the dog's name. When you call myDog.getName(), you get the name back as text.

Methods can take parameters too. You could write public void setAge(int newAge) { age = newAge; } to let other code change the dog's age.

Access modifiers: public, private, and default

An access modifier controls whether other code can see and use a field or method. The three most common are public (anyone can use it), private (only code inside this class can use it), and default (no modifier — only code in the same package can use it).

It is common practice to make fields private and methods public. This protects the data inside the object — other code cannot change a field directly, but must use a method to do it. Here is an example:

public class BankAccount {   private double balance;   public BankAccount(double startingBalance) {     balance = startingBalance;   }   public void deposit(double amount) {     balance = balance + amount;   }   public double getBalance() {     return balance;   } }

The balance field is private, so outside code cannot change it directly. The only way to change the balance is through the deposit() method, which ensures the operation is done correctly. This pattern is called encapsulation.

Creating and using objects from your class

Once you have written a class, you create objects from it using the new keyword. The syntax is: ClassName objectName = new ClassName(parameters);

Here is a complete example with a class and code that uses it:

public class Dog {   String name;   int age;   public Dog(String dogName, int dogAge) {     name = dogName;     age = dogAge;   }   public void bark() {     System.out.println(name + " says woof!");   } } public class Main {   public static void main(String[] args) {     Dog myDog = new Dog("Buddy", 3);     myDog.bark();   } }

When you run this code, it creates a Dog object named Buddy, then calls the bark() method on it. The output is "Buddy says woof!"

You can create multiple objects from the same class, and each one is independent:

Dog dog1 = new Dog("Buddy", 3); Dog dog2 = new Dog("Max", 5); dog1.bark(); dog2.bark();

This creates two separate Dog objects with different names and ages. Calling bark() on each one produces different output.

Common mistakes when writing classes

One frequent error is forgetting the curly braces or putting them in the wrong place. Every class, constructor, and method needs an opening brace { and a closing brace }. Check that they are balanced — each opening brace must have a matching closing brace.

Another mistake is using the wrong data type. If you declare a field as int age;, you cannot later assign text to it. Java will not let you write age = "three"; because "three" is a String, not an int.

A third common issue is forgetting the semicolon at the end of field declarations and statements. Every field declaration and every statement inside a method must end with a semicolon.

Finally, remember that the class name must match the filename exactly, including capitalization. If your class is called Dog, the file must be named Dog.java, not dog.java or Dogs.java.

Frequently Asked Questions

Do I have to write a constructor?

No. If you do not write one, Java creates an empty constructor automatically. But writing your own constructor is usually better because it lets you set up the object's fields when it is created, rather than leaving them empty.

What is the difference between a field and a variable?

A field belongs to the class and exists as long as the object exists. A variable is usually declared inside a method and only exists while that method is running. Fields are shared across all the methods in a class; variables are local to one method.

Can a method return different types of data?

No. When you write public String getName(), that method always returns a String. If you want to return different types, you need different methods, like public int getAge() for an int and public String getName() for a String.

What does the word "new" do?

The new keyword creates a new object in memory from the class blueprint and calls the constructor. Without new, you are just declaring a variable that can hold an object, but no actual object exists yet.

Can I have multiple constructors in one class?

Yes. You can write several constructors with the same name but different parameters. For example, one constructor might take a name and age, while another takes only a name. Java picks the right one based on what you pass in when you create the object.