Java Lesson 5: Classes and Objects

Java Lesson 5: Classes and Objects featured illustration

πŸ“Ž This article includes 1 downloadable practice file ↓

⏱ 1 min read

πŸ“˜ Java Beginner Course Β· Lesson 5 of 8

Advertisement
public class Invoice {
    record Line(String item, int qty, double rate) { double amount() { return qty * rate; } }
    private final String customer;
    private final List<Line> 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.

Advertisement

πŸ“Ž 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