Java programming course: 4.5 Class to model a zoo visitor

In the previous lesson you learnt about keywords this and super.


Class to model a zoo visitor

To model a zoo visitor let's assume you establish that only three pieces of information are required; their name, email address and the animal they are sponsoring, although they might not be sponsoring one. Create a Visitor class in virtualzoo.core with these as instance variables:

package virtualzoo.core;

public class Visitor {
    
    private String name;
    private String email;
    private Animal sponsoredAnimal;
    
}
 

You will note that the sponsoredAnimal variable is declared to be of type Animal. This will enable it to hold any Animal object, i.e., any of the subclasses Lion, Monkey or Penguin.

NetBeans includes facilities to generate code based on your instance variables, and uses the this keyword in its generated code. In the Visitor class right-click on the source code area at the point where you want the constructor to be and select Insert Code..., followed by Constructor...

In the Generate Constructor dialog ensure all of the instance variable checkboxes are checked and click Generate:

Generate constructor dialog

NetBeans will generate the following code:

public Visitor(String name, Email email, Animal sponsoredAnimal) {
    this.name = name;
    this.email = email;
    this.sponsoredAnimal = sponsoredAnimal;
}
 

Immediately after the constructor right-click the source code again, select Insert Code... followed by Getter and Setter...

Ensure the checkboxes are all checked and click Generate to produce the necessary methods. The source file should now look as follows:

package virtualzoo.core;

public class Visitor {
    
   private String name;
   private String email;
   private Animal sponsoredAnimal;

   public Visitor(String name, String email, Animal sponsoredAnimal){
       this.name = name;
       this.email = email;
       this.sponsoredAnimal = sponsoredAnimal;
   }

   public String getEmail() {
       return email;
   }

   public void setEmail(String email) {
       this.email = email;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public Animal getSponsoredAnimal() {
       return sponsoredAnimal;
   }

   public void setSponsoredAnimal(Animal sponsoredAnimal) {
       this.sponsoredAnimal = sponsoredAnimal;
   }

}
 

You can also use the code generator to generate a toString() method, although you should modify it to be as follows:

@Override
public String toString() {
    return getName();
}
 

You will recall from the requirements that not all visitors will necessarily be sponsoring an animal. This leads to the question of what value to store in its allocated instance variable sponsoredAnimal if they aren't sponsoring an animal?

Java contains a special value called null which represents no value. It can only be used with reference variables to indicate that while the variable exists it is not currently pointing to an object. Consider the following code:

Animal clarence;                            // statement 1
clarence = new Lion("Clarence", "m", 9);    // statement 2
 

After statement 1 has been executed the reference variable clarence exists but is null; that is, it has not yet been assigned to any object. Statement 2 then goes on to instantiate an object of type Lion (using the new keyword), and once the object exists the clarence reference variable is assigned to point at this object, so the reference will no longer be null.

It is also possible to explicitly set a variable to be null if need be. For example, a third statement could be added:

clarence = null;				// statement 3 

After statement 3 completes, leo is null again and no longer points to any object. The Lion object which was created no longer has any variables pointing to it, which means it can never again be used (you would have to create a new object over again if you needed it).

When an object no longer has any variables pointing to it the Java runtime environment realises that it can no longer ever be accessed and will, at some point, reclaim the memory space allocated to it. This is a process which happens automatically behind the scenes known as garbage collection, and you rarely need to be concerned with it[1].

[1 ]Some other languages require the programmer to explicitly reclaim the memory of unreferenced objects. Java performs this process for you in the background, although it won't necessarily do it immediately.

The null value, therefore, seems like a reasonable candidate to use for the sponsoredAnimal variable, where it would in this case simply indicate "not sponsoring any animal". If you look at the constructor you will see it requires the sponsored animal to be specified as the third argument, so client objects that need to use it would have to use the following for these situations:

Visitor mary = new Visitor(“Mary Roberts”, “”, null); 

To make the client object's life more convenient you could define an overloaded constructor in Visitor that only requires the first two arguments, the favourite animal defaulting to null:

// Create a Visitor object without a sponsored animal
public Visitor(String name, String email) {
    this(name, email, null);
}
 

Now the client object can use this overloaded constructor to simplify matters slightly:

Visitor mary = new Visitor(“Mary Roberts”, “”); 

If the client object invokes the getSponsoredAnimal() method on a Visitor object whose sponsoredAnimal is null, then null is returned:

Animal marysFavouriteAnimal = mary.getSponsoredAnimal(); 

Executing the above will result in marysFavouriteAnimal being null. This does have implications since you cannot invoke a method on a null reference. For example, try the following in VirtualZoo:

Visitor mary = new Visitor("Mary Smith", "");
Animal marysFavouriteAnimal = mary.getFavouriteAnimal();
int age = marysFavouriteAnimal.getAge();
 

You will receive a NullPointerException, which means that the program "crashed" at that point since it doesn't know how to proceed. This is something that the programmer must prevent, and you will learn how and more about exceptions in Section 7.


In the next lesson you will learn about Java interfaces.

Next lesson: 4.6 Java interfaces 


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Saturday, 13 December 2025

Captcha Image