Session 3 |
Simple object class and client class
In order to create new data types and use them, we need to create:
- an object class (base class, object code) - a class without main method in which a new data type, an object state and behavior are defined;
- a client class - a class with main method where specific instances of the object can be created.
In this example, we are going to create a simple object class Dog.
- An object class named Dog would be a prototype or blueprint for all dogs (instances) in our program. It would describe dogs in general without specific values neither behavior methods execution.
- The object class named Dog would also be our brand new data type.
- Inside the object class, we are going to declare a few variables which represent properties common to all dogs (e.g. color, age, size, breed). These variables are called instance variables, fields or attributes. Pay attention that we are not going to assign any values to these variables yet unless the value is common to all dogs.
// create a java file called Dog.java public class Dog { // Object fields are declared right after the class header String name; String breed; int age; String size; String color; }
To use the brand new data type Dog, we need another class - client class - with the main method:
// create a new java file called Execute.java public class Execute{ public static void main(String[] args){ Dog liza = new Dog(); } }
Now we have created an instance of object class Dog. However, this instance liza does not represent our labrador Liza yet because we have not given any values to instance variables name, breed, age, size, color. In fact, at the moment these variables contain the default values such as null or 0.
Self-assessment
Add the following line of code System.out.println(liza.breed);
into the main methods.
What is the result?
There are several ways to set values to the variables.
Option 1. Change the object definitions in the object class:
// modify java file called Dog.java public class Dog { // Object fields String name = "Liza"; String breed = "labrador"; int age; String size; String color; }
Option 2. Initialize variables in the client class:
// modify java file called Execute.java public class Execute{ public static void main(String[] args){ Dog liza = new Dog(); liza.name = "Liza"; liza.breed = "labrador"; // Once the instance field is set, // we can refer to it by object_name.instance_field (so called dot notation) System.out.println(liza.name + " is a " + liza.breed); } }
Option 3. Use a powerful constructor. This option will be explained in detail on next page.
Session 3 |