Up to this point, today’s lesson has been pretty theoretical. In this section, you’ll create a working example of the Motorcycle class so that you can see how instance variables and methods are defined in a class in Java.
You’ll also create a Java application that creates a new instance of the Motorcycle class and shows its instance variables.

Tip
The indentation of each part of the class isn’t important to the Java compiler. Using some form of indentation, however, makes your class definition easier for you and other people to read. The indentation used here, with instance variables and methods indented from the class definition, is the style used throughout this book. The Java class libraries use a similar indentation. You can choose any indentation style that you like.

Ready? Let’s start with a basic class definition. Open the text editor you’ve been using to create Java source code and enter the following (remember, upper- and lowercase matters):
      class Motorcycle {
        }

Congratulations! You’ve now created a class. Of course, it doesn’t do very much at the moment, but that’s a Java class at its very simplest.

First, let’s create some instance variables for this class-three of them, to be specific. Just below the first line, add the following three lines:
String make;
String color;
boolean engineState = false;

Here you’ve created three instance variables: Two, make and color, can contain String objects (a string is the generic term for a series of characters; String, with a capital S, is part of that standard class library
mentioned earlier). The third, engineState, is a boolean variable that refers to whether the engine is off or on; a value of false means that the engine is off, and true means that the engine is on. Note that boolean is
lowercase b.

Tip
The indentation of each part of the class isn’t important to the Java compiler. Using some form of indentation, however, makes your class definition easier for you and other people to read. The indentation used here, with instance variables and methods indented from the class definition, is the style used throughout this book. The Java class libraries use a similar indentation. You can choose any indentation style that you like.
Tip
The indentation of each part of the class isn’t important to the Java compiler. Using some form of indentation, however, makes your class definition easier for you and other people to read. The indentation used here, with instance variables and methods indented from the class definition, is the style used throughout this book. The Java class libraries use a similar indentation. You can choose any indentation style that you like.

Now let’s add some behavior (methods) to the class. There are all kinds of things a motorcycle can do, but to keep things short, let’s add just one method-a method that starts the engine. Add the following lines below the
instance variables in your class definition:

				
					   void startEngine() {
       if (engineState == true)
           System.out.println("The engine is already on.");
       else {
           engineState = true;
           System.out.println("The engine is now on.");
       }
   }

				
			

Listing 2.1. The Motorcycle.java file.

				
					1:class Motorcycle {
    2:
    3: String make;
    4: String color;
    5: boolean engineState = false;
    6:
    7: void startEngine() {
    8:     if (engineState == true)
    9:         System.out.println("The engine is already on.");
   10:     else {
   11:         engineState = true;
   12:         System.out.println("The engine is now on.");
   13:     }
   14: }
   15:}

				
			
Tip
The indentation of each part of the class isn’t important to the Java compiler. Using some form of indentation, however, makes your class definition easier for you and other people to read. The indentation used here, with instance variables and methods indented from the class definition, is the style used throughout this book. The Java class libraries use a similar indentation. You can choose any indentation style that you like.

Before you compile this class, let’s add one more method just below the startEngine() method (that is, between lines 14 and 15). The showAtts() method is used to print the current values of all the instance
variables in an instance of your Motorcycle class. Here’s what it looks like:

				
					   void showAtts() {
       System.out.println("This motorcycle is a "
           + color + " " + make);
       if (engineState == true)
           System.out.println("The engine is on.");
       else System.out.println("The engine is off.");
   }

				
			

The showAtts() method prints two lines to the screen: the make and color of the motorcycle object and whether the engine is on or off.

Now you have a Java class with three instance variables and two methods defined. Save that file again, and compile it using one of the following methods:

When you run this little program using the java or Java Runner programs, you’ll get an error. Why? When you run a compiled Java class directly, Java assumes that the class is an application and looks for a main()
method. Because we haven’t defined a main() method inside the class, the Java interpreter (java) gives you an error something like one of these two errors:
In class Motorcycle: void main(String argv[]) is not defined
Exception in thread “main”: java.lang.UnknownError

To do something with the Motorcycle class-for example, to create instances of that class and play with them-you’re going to need to create a separate Java applet or application that uses this class or add a main()
method to this one. For simplicity’s sake, let’s do the latter. Listing 2.2 shows the main() method you’ll add to the Motorcycle class. You’ll want to add this method to your Motorcycle.java source file just before
the last closing brace (}), underneath the startEngine() and showAtts() methods.

.

Listing 2.2. The main() method for Motorcycle.java.

				
					    1: public static void main (String args[]) {
    2:    Motorcycle m = new Motorcycle();
    3:    m.make = "Yamaha RZ350";
    4:    m.color = "yellow";
    5:    System.out.println("Calling showAtts...");
    6:    m.showAtts();
    7:    System.out.println("--------");
    8:    System.out.println("Starting engine...");
    9:    m.startEngine();
   10:    System.out.println("--------");
   11:    System.out.println("Calling showAtts...");
   12:    m.showAtts();
   13:    System.out.println("--------");
   14:    System.out.println("Starting engine...");
   15:    m.startEngine();
   16:}

				
			

Out Put

				
					   Calling showAtts...
   This motorcycle is a yellow Yamaha RZ350
   The engine is off.
   --------
   Starting engine...
   The engine is now on.
   --------
   Calling showAtts...
   This motorcycle is a yellow Yamaha RZ350
   The engine is on.
   --------
   Starting engine...
   The engine is already on.

				
			

The first line declares the main() method. The first line of the main() method always looks like this; you’ll learn the specifics of each part later this week.

Line 2, Motorcycle m = new Motorcycle();, creates a new instance of the Motorcycle class and stores a reference to it in the variable m. Remember, you don’t usually operate directly on classes in your Java
programs; instead, you create objects from those classes and then call methods in those objects.

Lines 3 and 4 set the instance variables for this Motorcycle object: The make is now a Yamaha RZ350 (a very pretty motorcycle from the mid-1980s), and the color is yellow.

Lines 5 and 6 call the showAtts() method, defined in your Motorcycle object. (Actually, only 6 does; 5 just prints a message that you’re about to call this method.) The new motorcycle object then prints out the values
of its instance variables-the make and color as you set in the previous lines-and shows that the engine is off.

Line 7 prints a divider line to the screen; this is just for prettier output.

Line 9 calls the startEngine() method in the motorcycle object to start the engine. The engine should now be on.

Line 11 prints the values of the instance variables again. This time, the report should say the engine is now on.

Line 15 tries to start the engine again, just for fun. Because the engine is already on, this should print the message The engine is already on.

Listing 2.3 shows the final Motorcycle class, in case you’ve been having trouble compiling and running the one you’ve got (and remember, this example and all the examples in this book are available on the CD that
accompanies the book):

Listing 2.3. The final version of Motorcycle.java.

				
					    1: class Motorcycle {
    2: 
    3:    String make;
    4:    String color;
    5:    boolean engineState;
    6: 
    7:    void startEngine() {
    8:       if (engineState == true)
    9:           System.out.println("The engine is already on.");
   10:       else {
   11:           engineState = true;
   12:           System.out.println("The engine is now on.");
   13:       }
   14:    }
   15:    
   16:   void showAtts() {
   17:       System.out.println("This motorcycle is a "
   18:          + color + " " + make);
   19:       if (engineState == true)
   20:         System.out.println("The engine is on.");
   21:       else System.out.println("The engine is off.");
   22:    }
   23: 
   24:    public static void main (String args[]) {
   25:       Motorcycle m = new Motorcycle();
   26:       m.make = "Yamaha RZ350";
   27:       m.color = "yellow";
   28:       System.out.println("Calling showAtts...");
   29:       m.showAtts();
   30:      System.out.println("------");
   31:       System.out.println("Starting engine...");
   32:       m.startEngine();
   33:       System.out.println("------");
   34:       System.out.println("Calling showAtts...");
   35:       m.showAtts();
   36:       System.out.println("------");
   37:       System.out.println("Starting engine...");
   38:       m.startEngine();
   39:    }
   40:}

				
			
More Details
				
					// Define the class
public class MyClass {
    // Fields (attributes)
    private int myField;
    private String myString;

    // Constructor
    public MyClass(int myField, String myString) {
        this.myField = myField;
        this.myString = myString;
    }

    // Methods
    public void display() {
        System.out.println("Field: " + myField);
        System.out.println("String: " + myString);
    }

    // Getter and Setter methods
    public int getMyField() {
        return myField;
    }

    public void setMyField(int myField) {
        this.myField = myField;
    }

    public String getMyString() {
        return myString;
    }

    public void setMyString(String myString) {
        this.myString = myString;
    }
}

				
			

In this example:

  • We define a class called MyClass.
  • It has two fields, myField of type int and myString of type String.
  • There’s a constructor MyClass(int myField, String myString) that initializes the fields.
  • The display() method prints out the values of the fields.
  • Getter and setter methods are provided for accessing and modifying the fields.
  • You can then use this class in your Java program like this:
				
					public class Main {
    public static void main(String[] args) {
        // Create an object of MyClass
        MyClass obj = new MyClass(10, "Hello");

        // Call the display method
        obj.display();

        // Change the field values using setter methods
        obj.setMyField(20);
        obj.setMyString("World");

        // Call display again to see the changes
        obj.display();
    }
}

				
			

Out Put

				
					Field: 10
String: Hello
Field: 20
String: World

				
			

This is a very basic example, but it illustrates the structure of a class in Java and how you can create objects of that class to use its functionality.

Scroll to Top