CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Classes

Objects and Classes
Object
Instance variables

How to code instance variables

  • An instance variable may be a primitive data type, an object created from a Java class such as the String class, or an object created from a user-defined class such as the Product class.
  • To prevent other classes from accessing instance variables, use the private keyword to declare them as private.

The syntax for declaring instance variables

public|private primitiveType|ClassName variableName;

Examples

private double price;
private int quantity;
private String code;
private Product product;

Where you can declare instance variables

public class Product
{
    //common to code instance variables here
    private String code;
    private String description;
    private double price;

    //the constructors and methods of the class
    public Product(){}
    public void setCode(String code){}
    public String getCode(){ return code; }
    public void setDescription(String description){}
    public String getDescription(){ return description; }
    public void setPrice(double price){}
    public double getPrice(){ return price; }
    public String getFormattedPrice()
        { return formattedPrice; }

    //also possible to code instance variables here
    private int test;
}
Previous | Product class | Instance variables | Constructors | Methods | Overload methods | this | Next