Home

The Properties of a Class

 

The Public and Private Members of a Class

 

Introduction

 

Introduction

Many modern languages such as Visual Basic, C++ Builder, C#, or Delphi, have the concept of properties. The Java language does not currently support an official concept of properties but provides an alternate solution. In our Java lessons, we will use some techniques of imitating properties et create the same functionality.

Public and Private Fields

In Lesson 4, we learned how to create fields in a class. In a class, you can control how fields are accessed outside the class. You can create some fields that can be accessed outside the class and you can create other fields that other classes cannot access.

To create a field that can be accessed by only members of the same class, precede its data type with the private keyword. Here are examples:

public class House{
    String propertyNumber;
    private String kitchenCharacteristics;
    byte Stories;
    int bedrooms;
    private boolean bathroomIsDirty;
    double Value;
}

To create a field that can be accessed by members of the same class and members of other classes, precede its data type with the public keyword. Here are examples:

public class House{
    public String propertyNumber;
    private String kitchenCharacteristics;
    byte Stories;
    public int bedrooms;
    private boolean bathroomIsDirty;
    double Value;
}

In previous lessons, we did not specify whether a field was private or public but we were able to access any fields outside the class. This is possible because, by default, the members of a Java class are public. This means that if you do not use the public or the private keyword, a field is automatically made public.

Practical Learning Practical Learning: Creating Fields

  1. Start NetBeans
  2. Create a Java Application named DepartmentStore3
  3. To create a new class, in the Project window, right-click the DepartmentStore3 sub-folder under DepartmentStore3 -> New -> Java Class...
  4. Set the Class Name to StoreItem and click Finish
  5. Right-click under StoreItem and click Insert Code...
  6. In the menu that appears, click Constructor...

Public and Private Methods

As done for fields, you can control the access level of a method. To do this, you can precede the return value or void of a method with private or public. When a method has been marked as private, it can be accessed by methods of the same class but other classes cannot call that method. If a method was created as public, other methods of the same class can access it and instances of other classes can call it.

As mentioned for fields, the methods of a class are public by default. Therefore, if you want to hide a member of a class, you must explicitly mark it as public.

Introduction to Properties

 

Introduction

We saw that you could create (or make) a field as private to prevent its access from the outside of its class. Here is an example:

public class Square {
    private double side;
}

After making a field private, other classes can neither specify its value not retrieve. What if they need to? For example, if you want to create an object for the above Square class, you have no way of specifying the value of the side. To solve this problem, you create a property for the field. There are two types of properties: a reader and a writer.

Practical LearningPractical Learning: Introducing Properties

  1. In the class, create the following field:
     
    package departmentstore3;
    
    public class StoreItem {
        private long itemNumber;
    }
  2. Save the file

A Property Reader

A property is referred to as read if its role is only to make available the value of the field it represents. To create a read property, create a method with the following characteristics:

  1. Because the method is used to communicate with the outside world, it must be created as public
  2. The method must return the same type of value as the field it represents
  3. The name starts with get and ends with the name of the field with the first letter in upper case
  4. The method does not take any argument
  5. The method returns the field it represents

Here is an example:

public class Square{
    private double side;

    // This is a read property
    public double getSide() {
	return side;
    }
}

A read property is also referred to as read-only property because the clients of the class can only retrieve the value of the property but they cannot change it. Therefore, if you create (only) a read property, you should provide the users with the ability to primarily specify the value of the member variable. To do this, you can create a property method or a constructor for the class . Here is an example of such a constructor:

public class Square {
    private double side;

    // This is a read property
    public double getSide() {
        return side;
    }

    public Square(double s) {
        side = s;
    }
}

Once a read property has been created, other classes can access it, for example they can read its value as follows:

class Square {
    private double side;

    public Square(double s) {
        side = s;
    }

    // This is a read property
    public double getSide() {
        return side;
    }

    double calculatePerimeter() {
  	return side * 4;
    }
}

public class Exercise {
    public static void main(String[] args) {
	Square sqr = new Square(-24.86);

	System.out.println("Square Characteristics");
	System.out.printf("Side:      %.2f\n", sqr.getSide());
	System.out.printf("Perimeter: %.2f", sqr.calculatePerimeter());
    }
}

This would produce:

Square Characteristics
Side:      -24.86
Perimeter: -99.44

We described a property as serving as a door from outside to its corresponding field, preventing those outside classes from messing with the field. Notice that the Square class was given a negative value for the side and consequently produced a negative perimeter, which is usually unrealistic. In this case and others, while still protecting the field as private, you can use the read property to reset the value of the field or even to reject it. To provide this functionality, you can create a conditional statement in the read property to perform a checking process. Here is an example:

class Square {
    private double side;

    // This is a read property
    public double getSide() {
        // If the value given to the side is negative,
        // then set it to 0
        if (side < 0)
            return 0;
        else
            return side;
    }
}

Practical LearningPractical Learning: Creating a Property Reader

  1. In the Code Editor, right-click somewhere under the StoreItem line and click Insert Code...
  2. In the menu that appears, click Getter...
  3. In the Generate Getters dialog box, click the check box of itemNumber
     
    Generate Property
  4. Click Generate
  5. To add a few property readers, change the contents of the StoreItem.java file as follows:
    package departmentstore3;
    
    public class StoreItem {
        private long itemNumber;
        private String name;
        private String size;
        private double price;
    
        public StoreItem() {
            this.itemNumber = 0;
            this.name = "Unknown";
            this.size = "No Size";
            this.price  = 0.00;
        }
    
        // A constructor used to initialize an item
        public StoreItem(long number, String itemName,
                            String itemSize, double itemPrice) {
            this.itemNumber = number;
            this.name = itemName;
            this.size = itemSize;
            this.price  = itemPrice;
        }
    
        // A property for the stock number of an item
        public long getItemNumber() {
            return itemNumber;
        }
    
        // A property for the name of an item
        public String getName() {
            return name;
        }
    
        // A property for size of a merchandise
        public String getSize() {
            return size;
        }
    
        // A property for the marked price of an item
        public double getUnitPrice() {
            return price;
        }
    }
  6. Access the Main.java file and change it as follows:
    package departmentstore3;
    
    public class Main {
        private static StoreItem create() {
            StoreItem item = new StoreItem(622805,
    				"Black Leather Hand Bag",
    				"Medium", 85.95);
            return item;
        }
    
        private static void show(StoreItem si) {
            System.out.println("\n================================");
            System.out.println("/-/Arrington Department Store/-/");
            System.out.println("--------------------------------");
            System.out.println("Customer Invoice");
            System.out.printf("Item #:      %d\n", si.getItemNumber());
            System.out.printf("Description: %s\n", si.getName());
            System.out.printf("Item Size:   %s\n", si.getSize());
            System.out.printf("Unit Price:  %.2f\n", si.getUnitPrice());
            System.out.println("================================");
        }
        
        public static void main(String[] args) {
            StoreItem store = create();
            show(store);
        }
    }
  7. Execute the program and enter the values as follows:
     
    ================================
    /-/Arrington Department Store/-/
    --------------------------------
    Customer Invoice
    Item #:      622805
    Description: Black Leather Hand Bag
    Item Size:   Medium
    Unit Price:  $85.95
    ================================
    
    
    Black Leather Hand Bag
 
 

 
 

 

 

A Property Writer

In our Square class so far, we were using a constructor to create a value for the field. This meant that we had to always make sure that we knew the value of the field when we declared an instance of the class. Sometimes, this is not possible. For example, you cannot just call a constructor in the middle of the program, that is, after the object has been declared, to assign a new value to the field. To solve this kind of problem, you can provide a means of accessing the field any time to change its value.

Besides, or instead of, retrieving the value of a field of a class, you may want external classes to be able to change the value of that member. Continuing with our policy of hiding a field as private, you can create another type of property. a property is referred to as write if it can change (or write) the value of its corresponding field.

To get a write property, create a method using the following characteristics:

  1. Because the method is used to communicate with the outside world, it must be created as public
  2. Because the method is used by outside classes to assign a value to the field, the method is (or should be) created as void
  3. The name starts with set and ends with the name of the field with the first letter in upper case
  4. The method takes one argument that is the same type as the field it refers to
  5. In the body of the method, assign the argument to the field it represents

Here is an example:

public class Square {
    private double side;

    // This is a write property
    public void setSide(double value) {
        side = value;
    }
}

As you see, clients of a class can change the corresponding field of a member variable through the property writer. Based on this relationship, it is not unusual for a client of a class to make an attempt to "mess" with a field. For example, an external object can assign an invalid value to a member variable. Consider the following program:

class Square {
    private double side;

    // This is a read property
    public double getSide() {
        return side;
    }

    // This is a write property
    public void setSide(double value) {
        side = value;
    }

    public double calculatePerimeter() {
  	return side * 4;
    }

    public double calculateArea() {
        return side * side;
    }
}

public class Exercise {
    public static void main(String[] args) {
	Square sqr = new Square();

	sqr.setSide(-24.86);
	System.out.println("Square Characteristics");
	System.out.printf("Side:      %.2f\n", sqr.getSide());
	System.out.printf("Perimeter: %.2f\n", sqr.calculatePerimeter());
	System.out.printf("Area:      %.2f", sqr.calculateArea());

	System.out.println("\n");

	sqr.setSide(24.86);
	System.out.println("Square Characteristics");
	System.out.printf("Side:      %.2f\n", sqr.getSide());
	System.out.printf("Perimeter: %.2f\n", sqr.calculatePerimeter());
	System.out.printf("Area:      %.2f", sqr.calculateArea());
    }
}

This would produce:

Square Characteristics
Side:      -24.86
Perimeter: -99.44
Area:      618.02

Square Characteristics
Side:      24.86
Perimeter: 99.44
Area:      618.02

Because of this, and since it is through the writer that the external objects would change the value of the member variable, you can use the write property, rather than the reader, to validate or reject a new value assigned to the field. Remember that the client objects of the class can only read the value of the field through the read property. Therefore, there may be only little concern on that side.

A Read/Write Property

A property is referred to as read/write it has both a reader and a writer.

Practical LearningPractical Learning: Creating a Property Writer

  1. Access the StoreItem.java file
  2. Right-click somewhere under the StoreItem line and click Insert Code...
  3. In the menu that appears, click Setter...
  4. In the Generate Getters dialog box, click the check box of itemNumber and click Generate
  5. To add a few property writers, change the contents of the StoreItem.java file as follows:
    package departmentstore3;
    
    public class StoreItem {
        private long itemNumber;
        private String name;
        private String size;
        private double price;
    
        public StoreItem() {
            this.itemNumber = 0;
            this.name = "Unknown";
            this.size = "No Size";
            this.price  = 0.00;
        }
    
        // A constructor used to initialize an item
        public StoreItem(long number, String itemName,
                         String itemSize, double itemPrice) {
            this.itemNumber = number;
            this.name = itemName;
            this.size = itemSize;
            this.price  = itemPrice;
        }
    
        // A property for the stock number of an item
        public long getItemNumber() {
            return itemNumber;
        }
    
        public void setItemNumber(long itemNumber) {
            this.itemNumber = itemNumber;
        }
    
        // A property for the name of an item
        public String getName() {
            return name;
        }
    
        public void setName(String value) {
            this.name = value;
        }
    
        // A property for size of a merchandise
        public String getSize() {
            return size;
        }
    
        public void setSize(String value) {
            this.size = value;
        }
    
        // A property for the marked price of an item
        public double getUnitPrice() {
            return price;
        }
    
        public void setUnitPrice(double value) {
            if( this.price < 0)
                 this.price = 0.00;
            else
                 this.price = value;
        }
    }
  6. Access the Main.java file and change it as follows:
    package departmentstore3;
    
    public class Main {    
        private static StoreItem create() {
            StoreItem item = new StoreItem();
            
            item.setItemNumber(409527);
            item.setName("Manhattan - Cognac Calf");
            item.setSize("10 ½");
            item.setUnitPrice(275.95);
            
            return item;
        }
    
        private static void show(StoreItem si) {
            System.out.println("\n================================");
            System.out.println("/-/Arrington Department Store/-/");
            System.out.println("--------------------------------");
            System.out.println("Customer Invoice");
            System.out.printf("Item #:      %d\n", si.getItemNumber());
            System.out.printf("Description: %s\n", si.getName());
            System.out.printf("Item Size:   %s\n", si.getSize());
            System.out.printf("Unit Price:  %.2f\n", si.getUnitPrice());
            System.out.println("================================");
        }
        
        public static void main(String[] args) {
            StoreItem store = create();
            show(store);
        }
    
    }
  7. Execute the program and enter the values as follows:
     
    ================================
    /-/Arrington Department Store/-/
    --------------------------------
    Customer Invoice
    Item #:      0
    Description: Manhattan - Cognac Calf
    Item Size:   10 ½
    Unit Price:  275.95
    ================================
    
    
    Shoes

A Boolean property

You can create a property as a Boolean type. To do this, first specify its data type as bool. When treating the property, make sure its write property returns a Boolean type. A Boolean property is not like the other regular properties. It must specify its value as true or false. As done for Boolean methods, a Boolean property must produce only a true or false value.

Properties of External Classes

 

Properties and Enumerations

An enumeration is a technique of creating a data type that mimics an integer. After creating it, you can use it to create a property based on an enumeration. You use the same formula as one of the primitive data types we have used previously. Keep it mind that the property is of the type of an enumeration. This means that you cannot request its value like that of a primitive type and, when manipulating it, you must process it appropriately.

A Property of a Class Type 

Remember that, after creating a class, it becomes a data type in its own right. We have seen that you could declare a variable from it, you could pass it as argument, and you could return it from a method. As a normal data type, a class can be validated. This means that its value can be evaluated, rejected, or retrieved. Based on these characteristics of a class, you can create a property from it.

To create a property that is based on a class, primarily follow the same formulas we have applied to the other properties. The most important aspect to remember is that the class is composite. That is, it is (likely) made of fields of various types.

 
 
 

Previous Copyright © 2008-2016, FunctionX, Inc. Next