StaticTest2.java Questions

Instructions

  1. With the left mouse button pressed, drag the mouse across the contents of the program listing that is shown below. This will select the program listing. Then choose Copy from the Edit menu of your web browser to copy the program listing to the clipboard.
  2. Start your text editor and create a new file called StaticTest2.java. Choose Paste to paste the contents of the program listing from the clipboard into the new file.
  3. Save the file to disk and begin answering the questions that are shown below.
  4. When you need to look at the model answer, click here.
  5. Click here to go back to the tutorials menu.

Program listing

// STATIC VERSUS NON-STATIC TUTORIAL
// Copyright (C) 1998-2016 Davin Pearson
// Website: http://davin.50webs.com/java-tutorials
//
// This example is like StaticTest.java, except this time we
// use objects to make our code simpler.
//

class Character {

   // properties of the class...

   public String name;
   public String favouriteColour;
   public int    favouriteNumber;
  
   // constructor of the class...
 
   public Character(String aName, String aColour, int aNumber)
   {
      name            = aName;
      favouriteColour = aColour;
      favouriteNumber = aNumber;
   }

   public void displayMe()
   {
      System.out.println("Hello, my name is " + name);
      System.out.println("my favourite colour is " + favouriteColour);
      System.out.println("and my favourite number is " + favouriteNumber);
   }
} 

class StaticTest2
{ 
   public static void main(String[] args)
   {
      Character f = new Character("Fred Flintstone", "blue", 42);
   }
}

// QUESTIONS:
//
// (1) Add code to the StaticTest2 class to construct two
// new Character objects, one to represent "Barney Rubble"
// and the other to represent "Wilma Flintstone".  Make sure
// that the values of the properties are set appropriately.
// 
// (2) Add some code to the main method to call Fred
// Flintstone's displayMe method.
 
// HINT: Calling a non-static method.
// 
// (3) Add some code to the main method to print out Barney
// Rubble's favourite colour WITHOUT using Barney Rubble's
// displayMe method.
 
// HINT: Accessing a non-static property.
// 
// (4) Why is it better to have a Character class for a
// general character rather than a class for each character?
//
// HINT: Imagine that you had 100 characters to consider.
// 
// (5) Under what circumstances would it be better to have a
// separate class for each character, rather than a separate
// object for each character?
//