Skip to main content
Logo image

Chapter 8 Classes

Now we finally get to the heart of Java: classes and objects.
Java is an object-oriented programming language. That means that one of the primary ways of designing and organizing a Java program is in terms of objects. All values in Java that are not primitive are objects. Arrays are not primitive, so they are one kind of object. But usually when we talk about objects we are talking about values defined by classes, the topic of this unit.
Classes let us define new data types way that combines the definition of the data that makes up the values and the code that operates on that data into a single unit. One consequence of this organization is it lets us treat objects as somewhat of a black box, a thing we can use without having to know all the details of how it works on the inside. We’ve already seen how that can work when we’ve used String and Turtle objects. We don’t know exactly how, say, indexOf works or what exactly happens when we tell a Turtle to got forward(), but we can use those methods in our programs as long as we understand what they do.
But we can also open up the box and look inside to see how a class works. And we can write our own. In fact quite a lot of what we think of as Java, is really just classes written in Java that we could write ourselves if they didn’t exist. There are a few classes, such as String, that are built into a Java at a slightly deeper level than something we could write. For instance, the fact that we can write String literals in double quotes in our Java programs is a feature of Java built into the Java compiler; we cannot define literal syntax for our own classes in the same way. But even most of the String class is written in java
In this unit we’ll look first at classes from inside the box to see how they are structured on the inside. Then, with some of the mystery hopefully dispelled, we’ll look at the details of using classes and objects.