Java Creating Classes

In the last lesson you learned an introduction to classes. Now for the hands-on part. We type a class from the first brace to the last, add fields and methods, and run it.

πŸ€” Why we need to write our own classes

Java gives you ready-made classes like String and Scanner. But those only model things Java already knows about, not your program.

  • Java has no Student, no Car, no Product class for your app.
  • Those things live only in your project, so you describe them yourself.

Picture a shop program tracking products. Without a class, name and price scatter into loose variables.

// ❌ Loose variables, nothing says they belong together
String productName = "Pen";
double productPrice = 1.5;

There is no link between them, and a second product gets messy fast. We want to create a class called Product that holds a name and a price as one unit.

🧱 The class keyword and the body

Every class starts the same way: the word class, a name, then a pair of curly braces. The space inside the braces is the class body.

Here is the smallest class you can write.

class Product {
}
  • class tells Java a blueprint starts here.
  • Product is the name we picked.
  • The braces { and } mark the start and end of the body.
  • The body is empty, so this does nothing yet, but it compiles as a real class.

Naming rules:

  • Start with a capital letter and use a noun, since a class stands for a thing: Product, Student, Car.
  • No numbers at the start, no spaces.
  • For two words, join and capitalize each: BankAccount.

🧩 Declaring fields with types

The data items inside a class are called fields (also called instance variables, same thing).

  • A field is a variable that lives in the class body, not inside a method.
  • You declare it like any variable: type first, then name, then a semicolon.

This class gives Product two fields, a name and a price.

class Product {
String name; // a field of type String
double price; // a field of type double
}
  • String name; gives every product a text name. String is the type, name is the field name.
  • double price; gives every product a decimal price. double holds numbers with a fractional part, like 1.5.
  • The order is fixed: type, name, semicolon.
  • These fields describe the shape of every Product. They hold no values yet; each object fills its own slots later.

You can give a field any type you know. Here are a few common ones.

class Person {
String name; // text
int age; // whole number
double height; // decimal number
boolean isMember; // true or false
}

A class can mix as many fields of as many types as you need.

βš™οΈ Writing methods

Fields are the data. Methods are the behavior, the actions an object can perform. They go in the class body alongside the fields, each made of a return type, a name, parentheses for inputs, and a body in braces.

This class adds a show method that prints the product’s name and price.

class Product {
String name;
double price;
void show() {
System.out.println(name + " costs " + price);
}
}
  • void is the return type, meaning the method gives nothing back. It just does a job and finishes.
  • show is the method name. Use verbs, because methods do things.
  • The empty () means it takes no inputs.
  • Inside the braces is the body that runs when you call it.
  • name and price have no object in front, so they mean the fields of this same object. A method inside the class reaches its own fields directly.

A method can also accept values inside its parentheses. Those values are called parameters. This version adds an applyDiscount method that lowers the price by an amount you pass in.

class Product {
String name;
double price;
void show() {
System.out.println(name + " costs " + price);
}
void applyDiscount(double amount) {
price = price - amount;
}
}
  • double amount is a parameter, a slot that receives a value when the method is called.
  • applyDiscount(0.5) arrives with amount equal to 0.5, and price drops by that much.
  • One method, reused with any amount you like.

πŸ” Access modifiers, a quick preview

Words like public and private are access modifiers. They control who can touch a field or method.

  • public means anyone, anywhere in the program, can use it.
  • private means only code inside the same class can use it.

A later lesson covers this fully. For now, here is the shape.

class Product {
private double price; // hidden, only this class touches it
public void show() { // open, anyone can call it
System.out.println("Price: " + price);
}
}

The idea is to hide raw data with private and offer safe public methods. We go deep into this soon; for now keep using plain fields.

πŸ“„ The file name must match the public class

A rule that trips up most beginners: a public class must live in a file with the same name plus .java.

  • A public class Product must be saved as Product.java.
  • Not product.java, not MyProduct.java. The capital letters must match too.
// βœ… This must be saved in a file named Product.java
public class Product {
String name;
double price;
}

If the names do not match, Java refuses to compile.

Compiler error

Product.java:1: error: class Product is public, should be declared in a file named Product.java
  • It keeps projects tidy: to find Product, you open Product.java.
  • A file can hold more than one class, but only one can be public, and that one decides the file name.

πŸš— A complete class, built step by step

Let’s build one full Car class from nothing to a working program. First, the empty shell.

class Car {
}

Next, give it fields. A car has a brand, a model, and a current speed.

class Car {
String brand;
String model;
int speed;
}

Now add behavior. A car can speed up, slow down, and report its status.

class Car {
String brand;
String model;
int speed;
void accelerate(int amount) {
speed = speed + amount;
}
void brake(int amount) {
speed = speed - amount;
}
void status() {
System.out.println(brand + " " + model + " is going " + speed + " km/h");
}
}

That class has state in its fields and behavior in its methods. To use it we need a main method, which lives in its own class. There we build a Car, set its fields, call its methods, and print the result.

public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // βœ… build a Car object
myCar.brand = "Toyota"; // set its fields
myCar.model = "Corolla";
myCar.speed = 0;
myCar.accelerate(60); // call a method on the object
myCar.status();
myCar.brake(20);
myCar.status();
}
}
class Car {
String brand;
String model;
int speed;
void accelerate(int amount) {
speed = speed + amount;
}
void brake(int amount) {
speed = speed - amount;
}
void status() {
System.out.println(brand + " " + model + " is going " + speed + " km/h");
}
}
  • new Car() builds one real Car object; myCar refers to it.
  • The dot sets each field, like myCar.brand = "Toyota".
  • myCar.accelerate(60) runs accelerate on this car, raising speed to 60.
  • myCar.status() prints the current state.
  • myCar.brake(20) lowers speed to 40, then we print again.
  • The dot means β€œthis part of this object”, so each call works on the exact object before it.

Output

Toyota Corolla is going 60 km/h
Toyota Corolla is going 40 km/h

That is a class built from an empty brace to a running program: fields, methods, an object, and output.

πŸ—‚οΈ Multiple classes in a project

Real programs are many classes working together. Above, Main and Car share one file, which is fine for learning.

  • In larger projects, give each class its own file: Car in Car.java, main in Main.java.
  • Classes in the same project folder see each other with no import needed.

Here is the same program split across two files.

Car.java
public class Car {
String brand;
String model;
int speed;
void accelerate(int amount) {
speed = speed + amount;
}
void status() {
System.out.println(brand + " " + model + " is going " + speed + " km/h");
}
}
Main.java
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.brand = "Honda";
myCar.model = "Civic";
myCar.accelerate(80);
myCar.status();
}
}

Both classes are public and each matches its file name. Main creates and uses a Car from a separate file, and Java pulls both together at compile time.

Output

Honda Civic is going 80 km/h

One public class per file

You can put several classes in one file, but only one of them may be public, and the file name must match that public one. Splitting each class into its own file keeps things easy to find as your project grows.

⚠️ Common Mistakes

  • File name does not match the public class. The file for public class Product must be Product.java, capitals included.
// ❌ saved in a file called product.java (wrong case)
public class Product { }
// βœ… saved in a file called Product.java
public class Product { }
  • Missing or unmatched braces. Every { needs a }. Forget the last one and Java cannot tell where the class ends.
// ❌ the closing brace of the class is missing
class Car {
String brand;
void status() {
System.out.println(brand);
}
// βœ… every { has a matching }
class Car {
String brand;
void status() {
System.out.println(brand);
}
}
  • Putting code outside a method. Action statements like printing must live inside a method. The class body holds only fields and methods, not loose action code.
// ❌ a print statement sitting loose in the class body
class Car {
String brand;
System.out.println(brand); // not allowed here
}
// βœ… the action goes inside a method
class Car {
String brand;
void status() {
System.out.println(brand);
}
}
  • Lowercase class names. class car works but breaks convention. Use class Car.

βœ… Best Practices

  • Name a class with a capital noun. Car, Product, Student.
  • Name methods with verbs. accelerate, deposit, show.
  • Keep fields and their methods together. Behavior belongs in the same class as the data it uses.
  • Give each public class its own file. Keeps the project tidy and easy to navigate.
  • Use clear, plain field names. price, speed, name, no comment needed.

🧩 What You’ve Learned

Nice work, you can now write a class on your own.

  • βœ… A class starts with the class keyword, a capital-noun name, and a pair of braces for the class body.
  • βœ… Fields are declared inside the body as type, then name, then a semicolon, like double price;.
  • βœ… Methods hold the behavior and are written inside the class with a return type, a name, parentheses, and a body.
  • βœ… public and private are access modifiers that control who can use a field or method, covered fully later.
  • βœ… A public class must be saved in a file with the exact same name plus .java.
  • βœ… A project can have many classes, and giving each its own file keeps things tidy.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    How do you start declaring a class in Java?

    Why: A class begins with the class keyword, a name, and a pair of curly braces for the body.

  2. 2

    How is a field declared inside a class?

    Why: You write the type first, then the field name, then a semicolon, like double price;.

  3. 3

    What must be true about a file holding a public class named Product?

    Why: A public class must live in a file whose name matches the class name plus .java.

  4. 4

    Where must action code like System.out.println go?

    Why: Statements that do something must live inside a method; the class body itself only holds fields and methods.

πŸš€ What’s Next?

You can write a class now, but we have been creating objects the long way, setting each field one line at a time. That is fine, but it gets repetitive fast. Next we will focus on creating objects properly with new, see how each object lives on its own, and get ready for a cleaner way to set them up. Let’s keep going.

Java Creating Objects

Share & Connect