Understanding instance and class members (reprint from http://download.oracle.com/javase/tutorial/ja)

Source: Internet
Author: User
Understanding instance and Class Members In this section, we discuss the use of staticKeyword 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 copiesInstance variables. In the case ofBicycleClass, the instance variables arecadence,gear, Andspeed. EachBicycleObject 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 withstaticModifier. fields that havestaticModifier in their Declaration are calledStatic FieldsOrClass 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 numberBicycleObjects 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 manyBicycleObjects 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    private static 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 useBicycleConstructor to setidInstance variable and incrementnumberOfBicyclesClass 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 number        id = ++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 havestaticModifier in their declarations, shocould 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 cocould Add a static method toBicycleClass to accessnumberOfBicyclesStatic Field:

public static int getNumberOfBicycles() {    return numberOfBicycles;}

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

  • Instance methods can access instance variables and instance methods directly.
  • Instance methods can access class variables and class methods directly.
  • Class methods can access class variables and class methods directly.
  • Class MethodsCannotAccess instance variables or instance methods directly-they must use an object reference. Also, class methods cannot usethisKeyword as there is no instancethisTo refer.
Constants

ThestaticModifier, in combination withfinalModifier, is also used to define constants.finalModifier 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 Compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that PI actually shocould be 3.975 ), you will need to recompile any classes that use this constant to get the current value.
The BicycleClass

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

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;        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;    }}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.