Java Classes and Objects: Object-Oriented Basics
Introduction
Java is an object-oriented language: you model things as classes and create objects from them. A class describes the data (fields) and behavior (methods) of a concept, and each object is a concrete instance. This tutorial builds a small Student class step by step.
Prerequisites
- JDK installed and working
- Ability to compile and run a Java program
Step-by-Step Guide
Step 1: Declare a class with fields and a constructor
Fields hold an object's data. Marking them private hides them from outside code (encapsulation). The constructor runs when you create an object and sets the initial state.
public class Student {
private String name;
private int grade;
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
}Step 2: Add methods
Methods define what an object can do. Provide getters to expose values safely instead of making fields public.
public String getName() {
return name;
}
public void promote() {
grade++;
}
public String describe() {
return name + " is in grade " + grade;
}Step 3: Create and use objects
Use the new keyword to create an object, then call its methods. Each object keeps its own copy of the fields.
public class Main {
public static void main(String[] args) {
Student ava = new Student("Ava", 8);
Student ben = new Student("Ben", 7);
ava.promote();
System.out.println(ava.describe()); // Ava is in grade 9
System.out.println(ben.describe()); // Ben is in grade 7
}
}Step 4: Keep data private
Because grade is private, other classes can't set it to an invalid value directly. They must go through methods you control, which is the main benefit of encapsulation.
FAQs
- What is the difference between a class and an object?
- A class is a blueprint that defines fields and methods. An object is a specific instance created from that blueprint.
- What does the this keyword mean?
- this refers to the current object. It's commonly used in constructors to tell a field apart from a parameter with the same name.
Summary
Define classes to model real-world concepts, set up state in constructors, expose behavior through methods, and keep fields private. These basics lead naturally to inheritance and interfaces.
Comments
Log in or create a free account to join the discussion.