Skip to lesson

Classes: the blueprint of objects

A class is the blueprint of an object: one plan, written once, that lists the data and the actions every object of that kind will have.

What is a class?

A class is a blueprint (template) that describes the data (fields) and the actions (methods) its objects will have. A class is a type you define; writing a class creates no object.

A builder does not start with bricks. An architect first draws a blueprint: one plan that says how many rooms there are and where the doors go. Many houses can then be built from that one plan, and the plan itself is not a house.

A class is that blueprint in your program. A Student class says what every student will have: data such as a name and marks, and actions such as showing a result. Writing the class builds no student; it only describes one.

So a class is a type you define, like int or String, but made for your own problem. The objects, the real students, are made from it later, while the program runs.

The class Student, with the fields name and marks, is written once. Three objects are built from it with new while the program runs: Aarav with 72 marks, Priya with 91 and Kavya with 85. Each object has its own values.

Writing a class: the general form and fields

A field (instance variable) is a variable declared inside a class but outside every method. It holds one piece of an object's data, and every object made from the class gets its own copy.

Every class follows one general form: the keyword class, a name, and a pair of braces. Inside the braces you write the class's members: the fields (its data) and the methods (its actions).

Syntax
class ClassName {
type fieldName;
returnType methodName() { statements }
}
  1. Line 1: fields: the data
  2. Line 2: methods: the actions
Java
class Student {    String name;    int rollNo;    int marks;    String course = "B.Tech";}

name, rollNo, marks and course are fields: each is declared directly in the class body, with a type and a name. The rules for a field:

  • It sits in the class body, outside every method: a type and a name, like int marks;.
  • It may get a starting value where it is declared, like String course = "B.Tech";.
  • Every method of the class can use it by its plain name.
  • It is also called an instance variable: each object (instance) gets its own copy.

Methods and local variables

A method is a named block of code inside a class that does one action. A method without static is an instance method: it works for one object and uses that object's fields by their plain names.

A train ticket should print itself using its own passenger and fare. A method written in the class without static is an instance method: it can read the class's fields directly, with no parameters for them.

Java
class TrainTicket {    String passenger;    int fare;
    void printTicket() {        System.out.println("Passenger: " + passenger + ", Rs. " + fare);    }
    int fareFor(int seats) {        int total = fare * seats;        return total;    }}

printTicket() and fareFor(int seats) both use the fields passenger and fare. Inside fareFor, seats (a parameter) and total are local variables: they belong to that one method. The difference:

  • Field: declared in the class body; every method of the class can use it; it lasts as long as its object.
  • Local variable: declared inside a method (parameters too); only that method can use it; it is gone when the method ends, as in Local variables (opens in a new tab).

Example 1 · Mistake: using a local variable in another method

Exam.javaJava
public class Exam {    String subject;    int maxMarks;
    void showPercent(int got) {        double percent = got * 100.0 / maxMarks;        System.out.println(subject + ": " + percent + "%");    }
    void showLastPercent() {        System.out.println("Last result: " + percent + "%");    }}
Sample compiler output
Exam.java:11: error: cannot find symbol
        System.out.println("Last result: " + percent + "%");
                                             ^
  symbol:   variable percent
  location: class Exam
1 error

What this code does

  • subject and maxMarks are fields, so both methods may use them. percent is a local variable of showPercent, so it exists only inside that method.
  • In showLastPercent, javac finds no field and no local variable called percent, so it reports cannot find symbol and points at it.
  • Fix: a value that more than one method needs must be a field, for example double lastPercent;, stored by showPercent.

In Java Basics every method was static and got all its data through parameters (opens in a new tab). An instance method already has its object's fields, so it needs fewer parameters, and it can still have its own parameters and local variables.

Keep static on main. The methods of your own classes have no static in this module; Static and final (opens in a new tab) shows when a member should be static.

What may go directly inside a class body

Everything between a class's braces. It may hold only member declarations, such as fields and methods; steps like assignments and println calls must go inside a method.

You want every hostel to start with 120 rooms, so you write rooms = 120; in the class body. The class body holds only declarations; a step such as an assignment or a println must sit inside a method.

Example 2 · Mistake: a statement in the class body

Hostel.javaJava
public class Hostel {    String name;    int rooms;    rooms = 120;}
Sample compiler output
Hostel.java:4: error: <identifier> expected
    rooms = 120;
         ^
1 error

What this code does

  • rooms = 120; is a statement (a step), and the class body may hold only declarations, so javac expected the name of a new declaration there.
  • Fix: give the field its starting value where it is declared, int rooms = 120;. A step that must run goes inside a method.

Allowed directly in a class body: field declarations (with or without a starting value) and method declarations. Later modules add constructors and a few more members. Not allowed on their own: assignments, println, if, loops or any other step.

Fix the error

Fix the class body error

Read the error, then pick the line that fixes it.

Round 1 of 4

This class should give every hostel 120 rooms.

class Hostel {
String name;
rooms = 120;
}

Error

Hostel.java:3: error: <identifier> expected

Naming a class and saving it in a file

The bytecode file that javac makes for one class, named after the class. A .java file with three classes gives three .class files.

Java programmers everywhere follow the same naming conventions, so all code reads alike: a class is a singular noun in PascalCase, a field is a noun in camelCase, and a method is a verb in camelCase.

Java
class TrainTicket {          // class: PascalCase noun    String passenger;        // field: camelCase noun    int totalFare;    boolean isPaid;
    void printTicket() {     // method: camelCase verb        System.out.println(passenger + " paid: " + isPaid);    }}

So write Student, BankAccount and TrainTicket, not students or bank_account. Java is case-sensitive: marks and Marks, or show() and Show(), are different names.

A school program needs Student, Teacher and a class with main. One .java file may hold all of them, but at most one class can be public, and the file must be named after it.

Example 3 · Three classes in one file

SchoolApp.javaJava
class Student {    String name;    int rollNo;
    void showDetails() {        System.out.println(rollNo + ": " + name);    }}
class Teacher {    String name;    String subject;
    void showDetails() {        System.out.println(name + " teaches " + subject);    }}
public class SchoolApp {    public static void main(String[] args) {        System.out.println("School app started");    }}
Sample terminal run (Windows; on macOS list the files with ls *.class)
> javac SchoolApp.java
> dir /b *.class
SchoolApp.class
Student.class
Teacher.class
> java SchoolApp
School app started

What this code does

  • The file is SchoolApp.java, named after its only public class. javac makes one .class file per class: SchoolApp.class, Student.class and Teacher.class, as in Your first program (opens in a new tab).
  • You run the class that has main: java SchoolApp. Student has no main, so java Student stops with Error: Main method not found in class Student.
  • Both classes have a method called showDetails(). They do not clash, because each method belongs to its own class.

A class alone does nothing at runtime: it only describes objects, and the next lesson, Objects: instances of a class (opens in a new tab), creates objects from it with new.

Next step

Check your understanding

11 quick questions