Movatterモバイル変換


[0]ホーム

URL:


Documentation

The Java™ Tutorials
Classes and Objects
Classes
Declaring Classes
Declaring Member Variables
Defining Methods
Providing Constructors for Your Classes
Passing Information to a Method or a Constructor
Objects
Creating Objects
Using Objects
More on Classes
Returning a Value from a Method
Using the this Keyword
Controlling Access to Members of a Class
Understanding Class Members
Initializing Fields
Summary of Creating and Using Classes and Objects
Questions and Exercises
Questions and Exercises
Nested Classes
Inner Class Example
Local Classes
Anonymous Classes
Lambda Expressions
Method References
When to Use Nested Classes, Local Classes, Anonymous Classes, and Lambda Expressions
Questions and Exercises
Enum Types
Questions and Exercises
Trail: Learning the Java Language
Lesson: Classes and Objects
Section: More on Classes
Home Page >Learning the Java Language >Classes and Objects
« Previous • Trail • Next »

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.
SeeDev.java for updated tutorials taking advantage of the latest releases.
SeeJava Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
SeeJDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Understanding Class Members

In this section, we discuss the use of thestatic keyword to create fields and methods that belong to the class, rather than to an instance of the class.

Class Variables

When a number of objects are created from the same class blueprint, they each have their own distinct copies ofinstance variables. In the case of theBicycle class, the instance variables arecadence,gear, andspeed. EachBicycle object has its own values for these variables, stored in different memory locations.

Sometimes, you want to have variables that are common to all objects. This is accomplished with thestatic modifier. Fields that have thestatic modifier in their declaration are calledstatic fields orclass variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

For example, suppose you want to create a number ofBicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how manyBicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable,numberOfBicycles, as follows:

public class Bicycle {            private int cadence;    private int gear;    private int speed;            //add an instance variable for the object ID    private int id;        //add a class variable for the    //number of Bicycle objects instantiated    privatestatic int numberOfBicycles = 0;        ...}

Class variables are referenced by the class name itself, as in

Bicycle.numberOfBicycles

This makes it clear that they are class variables.


Note: You can also refer to static fields with an object reference like
myBike.numberOfBicycles
but this is discouraged because it does not make it clear that they are class variables.

You can use theBicycle constructor to set theid instance variable and increment thenumberOfBicycles class variable:

public class Bicycle {            private int cadence;    private int gear;    private int speed;    private int id;    private static int numberOfBicycles = 0;            public Bicycle(int startCadence, int startSpeed, int startGear){        gear = startGear;        cadence = startCadence;        speed = startSpeed;        //increment number of Bicycles        //and assign ID numberid = ++numberOfBicycles;    }    //new method to return the ID instance variable    public int getID() {        return id;    }        ...}

Class Methods

The Java programming language supports static methods as well as static variables. Static methods, which have thestatic modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in

ClassName.methodName(args)

Note: You can also refer to static methods with an object reference like
instanceName.methodName(args)
but this is discouraged because it does not make it clear that they are class methods.

A common use for static methods is to access static fields. For example, we could add a static method to theBicycle class to access thenumberOfBicycles static field:

publicstatic int getNumberOfBicycles() {    return numberOfBicycles;}

Not all combinations of instance and class variables and methods are allowed:

Constants

Thestatic modifier, in combination with thefinal modifier, is also used to define constants. Thefinal modifier indicates that the value of this field cannot change.

For example, the following variable declaration defines a constant namedPI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):

static final double PI = 3.141592653589793;

Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).


Note: If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called acompile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.

TheBicycle Class

After all the modifications made in this section, theBicycle class is now:

public class Bicycle {            private int cadence;    private int gear;    private int speed;            private int id;        privatestatic int numberOfBicycles = 0;            public Bicycle(int startCadence,                   int startSpeed,                   int startGear) {        gear = startGear;        cadence = startCadence;        speed = startSpeed;        id = ++numberOfBicycles;    }    public int getID() {        return id;    }    public static int getNumberOfBicycles() {        return numberOfBicycles;    }    public int getCadence() {        return cadence;    }            public void setCadence(int newValue) {        cadence = newValue;    }            public int getGear(){        return gear;    }            public void setGear(int newValue) {        gear = newValue;    }            public int getSpeed() {        return speed;    }            public void applyBrake(int decrement) {        speed -= decrement;    }            public void speedUp(int increment) {        speed += increment;    }}
« PreviousTrailNext »

About Oracle |Contact Us |Legal Notices |Terms of Use |Your Privacy Rights

Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved.

Previous page: Controlling Access to Members of a Class
Next page: Initializing Fields

[8]ページ先頭

©2009-2025 Movatter.jp