[public
]class
[extends
SuperClass]{
.
.
.
variable and method declarations
.
.
.
}
Every Java program contains at least one class. All but the most simple programs will have more than one class in existence at a time. Indeed, it is common to have many copies of the same class in existence at the same time. Of course a given thread of program flow can be only in one class's method at at time, but it can pass from class to class as a class method calls member methods from another class.
The body of the class contains the method and variable declarations that comprise the class. Method declarations are covered in a separate section. Variable declarations work like those in methods , except that you may prepend them with an access modifier like those used in methods.
The public
declaration of a class makes
the class available to other classes not in the
same source code file. There can only be one public class
per file, and it must bear the same name as the file (without
the .java extension). You can leave out
the public
declaration if there is only one
class in your program, or if your class will only be used by
other classes in the same .java file.
If a class extends
another class, it inherits
the member methods and variables of this other class, called
the super class. This means, basically, that if you have a copy
of a class, you also have a copy of the variables and methods
of the super class. This is an amazing invention that
saves a lot of code writing.
Double
.
The Double
contains
methods for dealing with primitive double
variables. For example, you might want to
convert a String
to a double
or vice versa. The Double
class
can be thought of as a bloated double
-
it contains a double
value as well as
a bunch of methods to operate on this value.
To create a Double
, you can use the
new
command. Consider the following:
Double val = new Double(3.4);This line declares the existence of the variable
val
of type Double
. It also assigns to val
a copy of the Double
class initialized to the value 3.4.
Notice that the new Double
declaration takes an
argument (in this case it is the value of the Double
).
A class can contain a method with the same name as the class,
called the constructor method. When
a copy of the class is created with a new
statement,
the constructor method will be called along with the correct arguments
provided. So the Double
class has a method declared in it that
looks something this:
public class Double { public Double(double value) { ... code here ... } ... code here ... }
main
method of the
Newton class,
which calls other class methods f
and fprime
.
![]() |
6.6 Methods |