CodeBlanks Logo Icon CodeBlanks

Attributes

Learn class and instance attributes.

Attributes: fields

The variables that hold a class's data are called fields. Each field is declared with a type and a name. The type determines what values the field can store; for example int for integers, double for decimals, String for text.

Example: class Product { String name; double price; int stock; }. Here three fields exist: name is a string, price a decimal, stock an integer. Before you assign a value, fields get defaults: numeric fields start at zero, string fields at null.

Assigning values to fields

You access an instance's field with a dot: object.field. Assignment uses the = sign. First create the instance with new, then assign values to its fields.

Example: Product p = new Product(); p.name = "Pen"; p.price = 12.5;. Here p is a Product instance. p.name accesses the name field and assigns a value. The instance must be created before assignment; otherwise you get an error.

Practice Define the Product class

Define a class named Product. Add three fields: String name, double price, int stock. In main create a Product instance, assign values to all three fields and print name and price on separate lines.

Starter code

Main.java
// Define the Product class
// Add three fields
// Instantiate and print in main

Sample solution

Main.java
class Product {
    String name;
    double price;
    int stock;
    public static void main(String[] args) {
        Product p = new Product();
        p.name = "Notebook";
        p.price = 25.0;
        p.stock = 10;
        System.out.println(p.name);
        System.out.println(p.price);
    }
}

Expected output

Notebook
25.0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match field types

Term Meaning
int Integer
double Decimal
String Text
boolean Logical

2 How do you assign 9.99 to the price field of a Product instance p?

  • price.Product = 9.99;
  • p.price = 9.99; Correct answer
  • Product.price = 9.99;
  • p(price, 9.99);

Explanation: P.price = 9.99; — instance name, dot, field name.

3 Complete the field declaration

Question
class Product {
    String name;
    ____ price;
}
Answer
class Product {
    String name;
    double price;
}

Explanation: The price field should be of type double.

All lessons in Intermediate