Classes
Classes are the building blocks of a Java application. A
class can contain methods (functions), variables,
initialization code, and, as we’ll discuss later, other classes. It serves
as a blueprint for making class instances, which are runtime objects
(individual copies) that implement the class structure. You declare a
class with the class keyword. Methods
and variables of the class appear inside the braces of the class
declaration:
classPendulum{floatmass;floatlength=1.0f;intcycles;floatgetPosition(floattime){...}...}
The Pendulum class contains three
variables: mass, length, and cycles. It also defines a method called getPosition(), which takes a float value as an argument and returns a
float value as a result. Variables and
method declarations can appear in any order, but variable initializers
can’t make “forward references” to other variables that appear later. Once
we’ve defined the Pendulum class, we
can create a Pendulum object (an instance of that
class) as follows:
Pendulump;p=newPendulum();
Recall that our declaration of the variable p doesn’t create a Pendulum object; it simply creates a variable
that refers to an object of type Pendulum. We still had to create the object,
using the new keyword, as shown in
the second line of the preceding code snippet. Now that we’ve created a
Pendulum object, we can access its
variables and methods, as we’ve already seen many times:
p.mass=5.0;floatpos=p.getPosition(1.0);
Two kinds of variables ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access