Chapter 6

Packages, Interfaces, and Encapsulation

If you want to find out if a particular programming language is object-oriented, ask if it supports inheritance, encapsulation, and polymorphism. You know by now that Java supports inheritance, which lets you design a class by deriving it from an existing one. This feature allows you to reuse existing code without copy-pasting reusable code fragments from other classes — the class NJTax from Listing 3-5 was designed this way.

In Lessons 6 and 7 you learn what encapsulation means and continue studying coding techniques and best practices. While this lesson will show you several short code examples illustrating certain programming topics, the next one will bring all the pieces you’ve learned so far together in one larger practical application.

Java Packages

A decently size project can have hundreds of Java classes and you need to organize them in packages (think file directories). This will allow you to categorize files, control access to your classes (see the section “Access Levels” later in this chapter), and avoid potential naming conflicts: If both you and your colleague coincidentally decide to call a class Util, this won’t be a problem as long as these classes are located in different packages.

Sometimes you’ll be using third-party libraries of Java classes written in a different department or even outside your firm. To minimize the chances that package names will be the same, it’s common to use so-called reverse domain name ...

Get Java® Programming 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.