Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures


Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips


Submit News
Search the site here...
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

The Java Lesson 16: An introduction to objects and object references

JavaFAQ Home » Java Lessons by Jon Huhtala Go to all tips in Java Lessons by Jon Huhtala

Bookmark and Share
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

The Java Lesson 16

An introduction to objects and object references


Learning and mastering object-oriented, Java programming can be confusing. In this lesson, some fundamental concepts are introduced that will help you understand what an object is and how to use one.

Until now, the primary use of classes in our programs has been simply to hold the main() method and other methods it might call. We have not used a class to create an object.

To realize the full potential of the Java language, a programmer must be able to:

  1. Define a class from which objects can be constructed. Such classes are said to be "instantiable".

  2. Construct and use objects of an instantiable class

For now, our emphasis is on constructing and using objects of an instantiable class. Defining an instantiable class will be covered later.

An instantiable class

  • Is a class from which objects can be constructed.

All classes presented thus far, though technically instantiable, would not be useful in constructing objects because their methods were declared static (the implications of which will be covered in a later lesson).

  • Is a custom data type (in contrast to a primitive data type). It describes something about which data is to be maintained and upon which processing is to be performed.

For example, if a company needs to maintain and process customer data, a Customer class can be defined. It can also create other classes (such as Order, Product, Part, Supplier, etc.) to maintain and process other types of data.

  • Encapsulates data and processing. It has its own variables and methods.

For example, a Customer class might have variables for holding a customer's account number, name, address, and credit limit and methods for storing a new address and changing their credit limit.

  • Defines what an object will look like. An instantiable class is like a template or pattern from which any number of objects can be constructed. The objects would all be similar, but have their own unique data values.

For example, after it has been defined the Customer class could be used to instantiate an infinite number of Customer objects. Each object would represent a single customer and have its own values for account number, name, address, and credit limit and its methods would store a new address and change the credit limit of its unique customer.

  • Has a constructor method. The purpose of the constructor is to perform initialization when an object of the class is instantiated. If one isn't explicitly defined, Java provides a default constructor. Many classes provide overloaded constructor methods to satisfy different construction needs.

For example, the Customer class may have one constructor that receives initial values for the customer's account number, name, address, and credit limit while another constructor might receive only the customer's name and address.

An object

  • Is a distinct instance of its class (an actual occurrence). It has its own set of variables (known as "instance variables") and methods (known as "instance methods"). When called, an object's instance methods automatically act upon its instance variables.

For example, if the Customer class is used to instantiate three Customer objects, each will have its own instance variables and instance methods:

Customer one

Customer two

Customer three

Bob Smith
123 Oak

Methods to process
object's data

Sue Green
918 Cedar

Methods to process
object's data

James Jones
442 Maple

Methods to process
object's data

The keyword this in Java is a reference to the current object.

  • May be accessed by using an object reference. An object reference is declared like a common variable. For example, the statement

Customer current;

creates an object reference with the identifier current that may be used to reference a Customer object. Because no value was assigned to current, it will have the initial value of null (a Java keyword that means no value). In order to use current, a Customer object must be constructed and assigned to it.

An object reference can only reference one object at a time but may be re-used.

  • Is instantiated by obtaining memory space and calling one of its constructor methods. For example, to instantiate a Customer object and assign it to current one could code

    current = new Customer();

where the new keyword obtains memory space for the object and Customer() calls the Customer class constructor method that requires no parameters.

It is possible to both declare and initialize an object reference in a single statement. This is much like declaring and initializing a variable with a single statement. For example,

Customer current = new Customer(3906, "Mary Brown", "118 Maple", 1000);

results in the following actions:

  1. Memory space for a new Customer object is obtained

  2. The Customer constructor method that receives values for the customer's account number, name, address, and credit limit is called to initialize the object's values

  3. The object reference current is created and assigned the location of the newly created Customer object

  • May have its instance methods called using dot notation. For example, the expression

current.setAddress("835 Pine")

would call the setAddress() instance method of the Customer object referenced by current.

Occasionally, it is convenient to instantiate an object and call one of its methods immediately without ever assigning it to an object reference. For example, the following statement uses Java's packaged Double class to convert the string literal "123.45" to its primitive double value:

double x = new Double("123.45").doubleValue();

The Double class is one of Java's "wrapper" classes (to be covered in a later lesson). All you need to know for now is that memory is obtained for a Double object and the string literal is passed to its constructor. The object's doubleValue() method is then called to retrieve the corresponding primitive value. It is this primitive value that is assigned to the double variable named x. The Double object is never assigned to an object reference and its existence is temporary.

  • Is automatically eligible for "garbage collection" when it can no longer be referenced. The JVM always has a low-priority thread running in background that looks for such objects. The memory space they occupied is returned to the memory "heap" for re-use.

For example, the following statement would schedule the garbage collection of the object referenced by current if no other reference exists for that object:

current = null;

While current would reference nothing at this point, it could later be assigned to another Customer object.

Note that the actual time at which an object is garbage colleted is up to the JVM. There is no way for a program to tell the JVM to "do it now".

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

Review questions

  1. If Order is a class having a constructor method that requires no parameters, which of the following would instantiate an Order object that may be referenced by the identifier temp? (choose two)

  1. Order temp;
    temp = Order();

  2. temp = new Order();

  3. Order temp;
    temp = new Order();

  4. Order temp = Order();

  5. Order temp = new Order();

  1. Assume that all unseen code is correct and that line numbers are for reference purposes only. If Part is a class having a constructor method that requires two parameters (an int for the part number and a string for the part name), which one of the statements below is true of attempting to compile and execut the following code fragment?

Part x;
x = new Part(3, "Widget");
x = new Part(7, "Framistan");
  1. a compile error will occur at line 1

  2. a compile error will occur at lines 2 and 3

  3. after executing these statements, x will reference the Part object for "Widget"

  4. after executing these statements, x will reference the Part object for "Framistan"

  5. after executing these statements, x will reference the Part objects for both "Widget" and "Framistan"

  1. Assume that Employee is an instantiable class having a constructor requiring no parameters and an instance method named getPayRate() requiring no parameters and returning a double value representing the employee's pay rate. If theEmp currently references an Employee object, which of the following code fragments will display the employee's pay rate and then schedule the object for garbage collection? (choose two).

  1. System.out.println(theEmp.getPayRate());
    theEmp = null;

  2. System.out.println(Employee.getPayRate());
    theEmp = null;

  3. System.out.println(theEmp.getPayRate());
    theEmp = new Employee();

  4. System.out.println(theEmp.getPayRate());
    theEmp = 0;

  5. System.out.println(Employee.getPayRate());
    theEmp = 0;

  1. True or False: An object reference must always be declared in order to instantiate and access the instance methods of an object.

  1. True

  2. False

 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search

Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy