What Beginning Java Programmers Should Know about Classes - dummies

What Beginning Java Programmers Should Know about Classes

By Barry Burd

When you start learning object-oriented programming in Java, you may think this class idea is a big hoax. Some geeks in Silicon Valley had nothing better to do, so they went to a bar and made up some confusing gibberish about classes. They don’t know what it means, but they have fun watching people struggle to understand it.

Well, that’s not what classes are all about. Classes are serious stuff. What’s more, classes are useful. Many reputable studies have shown that classes and object-oriented programming save time and money.

Even so, the notion of a class can be very elusive. Even experienced programmers — the ones who are new to object-oriented programming — have trouble understanding how an object differs from a class.

Classes, objects, and tables

Because classes can be so mysterious, let’s expand your understanding with another analogy. Check out the table of three purchases. The table’s title consists of one word (the word “Purchase”), and the table has three column headings — the words “amount,” “taxable,” and “total.” Well, the code has the same stuff — Purchase, amount, taxable, and total.

Think of the top part of the table (the title and column headings) as a class. This top part of the table tells user what it means to be a Purchase. (It means having an amount value, a taxable value, and a total value.)

image0.jpg

A class is like the top part of a table. And what about an object? Well, an object is like a row of a table. For example, you can create three objects (three instances of the Purchase class). The first object has amount value 20.00, taxable value true, and total value 21.00. In the table, the first row has these three values — 20.00, true, and 21.00.

image1.jpg

Some questions and answers

Here’s the world’s briefest object-oriented programming FAQ:

  • Can I have an object without having a class?

    No, you can’t. In Java, every object is an instance of a class.

  • Can I have a class without having an object?

    Yes, you can. It’s business as usual.

  • After I’ve created a class and its instances, can I add more instances to the class?

    Yes, you can. With no objects, three objects, four objects, or more objects, you still have the same old class.

  • Can an object come from more than one class?

    Bite your tongue! Maybe other object-oriented languages allow this nasty class cross-breeding, but in Java, it’s strictly forbidden. That’s one of the things that distinguishes Java from some of the languages that preceded it. Java is cleaner, more uniform, and easier to understand.