Java Creating Classes
Table of Contents + β
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, noCar, noProductclass 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 togetherString 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 {
}classtells Java a blueprint starts here.Productis 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 textname.Stringis the type,nameis the field name.double price;gives every product a decimalprice.doubleholds numbers with a fractional part, like1.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); }}voidis the return type, meaning the method gives nothing back. It just does a job and finishes.showis 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.
nameandpricehave 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 amountis a parameter, a slot that receives a value when the method is called.applyDiscount(0.5)arrives withamountequal to0.5, andpricedrops 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.
publicmeans anyone, anywhere in the program, can use it.privatemeans 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
Productmust be saved asProduct.java. - Not
product.java, notMyProduct.java. The capital letters must match too.
// β
This must be saved in a file named Product.javapublic 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 openProduct.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;myCarrefers 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/hToyota Corolla is going 40 km/hThat 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:
CarinCar.java,maininMain.java. - Classes in the same project folder see each other with no import needed.
Here is the same program split across two files.
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"); }}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/hOne 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 Productmust beProduct.java, capitals included.
// β saved in a file called product.java (wrong case)public class Product { }
// β
saved in a file called Product.javapublic 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 missingclass 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 bodyclass Car { String brand; System.out.println(brand); // not allowed here}
// β
the action goes inside a methodclass Car { String brand; void status() { System.out.println(brand); }}- Lowercase class names.
class carworks but breaks convention. Useclass 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
classkeyword, 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.
- β
publicandprivateare access modifiers that control who can use a field or method, covered fully later. - β
A
publicclass 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
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
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
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
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.