Java is an object-oriented language. Instead of keeping a program's data in lots of separate variables, you group related data and the actions that use it into objects.
A class is a blueprint. It describes what every object of that kind has (its fields) and what it can do (its methods). An object is one real thing built from that blueprint. A Dog class might describe that every dog has a name and an age and can bark; rex and bella would be two separate Dog objects, each with its own name and age.
In this lesson you'll write a class with fields, a constructor and methods, create objects from it, and protect its data with private fields.
Writing a class
class Dog {
String name;
int age;
void bark() {
System.out.println(name + " says woof!");
}
}nameandageare fields: variables that belong to each object.bark()is an instance method. It has nostatic, because it works on one particular dog's data.- Class names start with a capital letter:
Dog,BankAccount,Student.
A file may contain several classes, but only one can be public, and it must match the file name. In larger projects, each class usually gets its own file.
Creating objects with new
Dog rex = new Dog();
rex.name = "Rex";
rex.age = 3;
rex.bark(); // Rex says woof!new Dog() builds a new object in memory. The variable rex holds a reference to it. Use the dot to reach an object's fields and methods: rex.name, rex.bark(). Every object has its own copy of the fields, so changing rex.age doesn't affect any other dog.
Constructors and this
A constructor is a special method that runs when an object is created. It has the same name as the class and no return type:
class Dog {
String name;
int age;
Dog(String name, int age) {
this.name = name;
this.age = age;
}
}
Dog bella = new Dog("Bella", 5);this means "the object being built". this.name = name copies the parameter name into the object's field name. Constructors make sure every object starts life with sensible values.
Private fields and getters
To stop other code from putting objects into a broken state, mark fields private and provide methods to read or change them safely:
class BankAccount {
private double balance;
double getBalance() { return balance; }
void deposit(double amount) {
if (amount > 0) balance += amount;
}
}Now nobody can write account.balance = -500;. They have to go through deposit(), which checks the amount. Hiding data behind methods like this is called encapsulation.
Printing objects with toString
Printing an object you've written yourself gives something like Dog@1b6d3586: the class name and a code based on the object's hash code. Java calls the object's toString() method whenever it needs text, and the default version isn't very helpful. Write your own to describe the object:
class Dog {
String name;
int age;
@Override
public String toString() {
return name + " (" + age + ")";
}
}Now System.out.println(rex) prints Rex (3), and so does "Dog: " + rex. @Override asks the compiler to check that you really are replacing an inherited method, so a typo such as tostring is reported as an error. Comparing objects for equality works the same way: == checks whether two references point to the same object, and you override equals() to compare their contents.
Static members belong to the class
Fields and methods without static belong to each object. Fields and methods marked static belong to the class itself and are shared by every object:
class Ticket {
static int issued = 0; // one counter for all tickets
int number;
Ticket() {
issued++;
number = issued;
}
}After creating three tickets, each has its own number (1, 2 and 3), while Ticket.issued is 3. Use static fields for values that really are shared, such as counters and constants, and keep everything else as instance fields. The object model lesson explores references and object identity further.
Java Classes and Objects Syntax
Class syntax
class ClassName {
private Type field;
ClassName(Type field) {
this.field = field;
}
Type getField() {
return field;
}
}
ClassName obj = new ClassName(value);
obj.getField();Java Classes and Objects Summary
- A class is a blueprint; an object is one instance created with
new. - Fields store each object's data; instance methods work with that data.
- A constructor has the class's name, no return type, and sets up new objects.
this.fieldrefers to the current object's field.privatefields plus getter and setter methods protect an object's data.
Java Classes and Objects Examples
Each example shows the code, the output it produces and what each part does.
Two objects from one class
class Dog {
String name;
int age;
Dog(String name, int age) {
this.name = name;
this.age = age;
}
void bark() {
System.out.println(name + " says woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog rex = new Dog("Rex", 3);
Dog bella = new Dog("Bella", 5);
rex.bark();
bella.bark();
System.out.println(rex.name + " is " + rex.age);
}
}Rex says woof!
Bella says woof!
Rex is 3Line-by-line explanation
- Lines 5 to 8The constructor copies its parameters into the new object's fields.
- Lines 17 to 18Two separate objects, each with its own name and age.
- Lines 20 to 21Each call to bark() uses that object's own name.
A bank account with encapsulation
class BankAccount {
private String owner;
private double balance;
BankAccount(String owner) {
this.owner = owner;
this.balance = 0;
}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
boolean withdraw(double amount) {
if (amount > balance) {
return false;
}
balance -= amount;
return true;
}
double getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount("Sam");
acc.deposit(50);
acc.deposit(-20);
System.out.println("Withdraw 80: " + acc.withdraw(80));
System.out.println("Withdraw 30: " + acc.withdraw(30));
System.out.println("Balance: " + acc.getBalance());
}
}Withdraw 80: false
Withdraw 30: true
Balance: 20.0Line-by-line explanation
- Lines 2 to 3private fields can only be changed by the class's own methods.
- Line 11Negative deposits are ignored, so the -20 has no effect.
- Lines 17 to 19The method refuses withdrawals bigger than the balance.
- Line 33The only way to read the balance is through the getter.
A method that uses other objects' data
class Rectangle {
double width;
double height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
double area() {
return width * height;
}
boolean isBiggerThan(Rectangle other) {
return area() > other.area();
}
}
public class Main {
public static void main(String[] args) {
Rectangle a = new Rectangle(3, 4);
Rectangle b = new Rectangle(2, 5);
System.out.println("a: " + a.area() + ", b: " + b.area());
System.out.println("a bigger? " + a.isBiggerThan(b));
}
}a: 12.0, b: 10.0
a bigger? trueLine-by-line explanation
- Lines 10 to 12area() uses this rectangle's own width and height.
- Lines 14 to 16A method can take another object of the same class and compare them.
Common Java Classes and Objects Mistakes
Forgetting new
Dog rex;
rex.bark();Dog rex = new Dog("Rex", 3);
rex.bark();Declaring a variable doesn't create an object. Using one that was never created fails with an error.
Leaving out this in the constructor
Dog(String name, int age) {
name = name;
age = age;
}Dog(String name, int age) {
this.name = name;
this.age = age;
}Without this, the parameters are simply assigned to themselves and the fields stay empty.
Giving a constructor a return type
void Dog(String name) {
this.name = name;
}Dog(String name) {
this.name = name;
}With void, Java treats it as an ordinary method called Dog, and new Dog("Rex") won't compile.
Java Classes and Objects in Real Projects
Objects in real systems
An online shop might have Customer, Product, Cart and Order classes. A Cart object holds a list of Product objects and has methods like addItem() and getTotal(). Android apps, Spring web services and most Java libraries are built the same way, from many small classes working together.
Java Classes and Objects FAQ
What is the difference between a class and an object?
A class is the definition, written once in code, that describes fields and methods. An object is an instance created from it at run time with new, with its own values for the fields. One Dog class can produce any number of dog objects.
What happens if I don't write a constructor?
Java adds a default constructor with no parameters, which leaves fields at their default values: 0, false or null. As soon as you write any constructor yourself, the default one is no longer added, so new Dog() stops compiling unless you also write a no-argument constructor.
Can a class have more than one constructor?
Yes. Constructors can be overloaded like methods, as long as their parameter lists differ. One constructor can call another with this(...) as its first statement to avoid repeating code. See the constructor overloading lesson.
Should fields always be private?
In most classes, yes. Private fields let the class check every change and keep its objects valid, and they let you change how data is stored later without breaking other code. Constants marked public static final are a common exception, because they can't be changed.
What does a NullPointerException mean with objects?
A variable of a class type holds null when it doesn't point to any object, for example a field that was never assigned. Calling a method or reading a field through it, such as dog.bark(), throws a NullPointerException. Make sure every object is created with new before you use it.
Java Classes and Objects Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code that creates a new Book object.
Book b = Book("Dune");
Complete the constructor so it stores the title in the field.
class Book {
String title;
Book(String title) {
.title = title;
}
}
What is the difference between a class and an object?
What does this print?
Rectangle r = new Rectangle(2, 3);
r.width = 5;
System.out.println(r.area());
Why make fields private and add getters?
Java Classes and Objects Quiz
5 questions to check what you learned.
Which keyword creates a new object?
- new
- create
- make
- object
What is special about a constructor?
- It returns the object with return
- It has the same name as the class and no return type
- It must be static
- It can only take one parameter
Why make fields private?
- To make the program faster
- So other code must use methods, which can check values before changing them
- Because Java requires it
- To hide them from the compiler
What does
thisrefer to inside an instance method?- The class itself
- The main method
- The previous object created
- The object the method was called on
What does
this.name = name;do in a constructor?- Copies the parameter into the object's field with the same name
- Compares two names
- Creates a new object
- Prints the name