Java Lesson 5: Classes and Objects

📎 This article includes 1 downloadable practice file ↓

⏱ 1 min read

📘 Java Beginner Course · Lesson 5 of 8

“`java
public class Invoice {
record Line(String item, int qty, double rate) { double amount() { return qty * rate; } }
private final String customer;
private final List lines = new ArrayList<>();
Invoice(String customer) { this.customer = customer; }
void add(String item, int qty, double rate) { lines.add(new Line(item, qty, rate)); }
}
“`

A class is a blueprint; new Invoice("Iyer Stores") creates an object. Keep fields private and change them through methods, so rules (like positive quantity) are enforced in one place. A record is a compact class for plain data.

Code for this course follows standard, current syntax; we test JavaScript and PowerShell scripts before publishing, and R/Java/Rust examples are kept to core language features. Tell us if anything fails on your setup.

Practice

Read Invoice.java and run it.

📎 Practice files for this article

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong