Previous lesson Back to the front Next lesson

Take Car


Hi! Glad you're here - obviously that stuff about strings was no match for you. In this lesson we are going to do two things: create a program with two Java files, and make our own object type. Let's go!


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");
	}
}

There's our first class, saved in the file Hello.java. A class is a definition of an object type and exactly what it does. So there is a class called String, for example. In fact, right from our very first program, we have been using a class called Hello which we wrote ourselves in the file Hello.java. In fact, every Java program we write involves creating our own class, or object type.

The difference between a class and an object is like the difference between the design of a car, and an actual car. We can design a car without ever building it, but there is only one design (thinking of one particular model of car). Once we have a design, we can make as many cars as we like - but all using the same basic design. Think about strings - there is only one design which tells us what a string is, but we can make as many different strings as we like.

So let's design a car!


class Car {
}

I hope the yellow colour isn't too offensive. You should save this in a file called Car.java - so the first part of the file name matches the name of the class. Now remember that when we type javac Hello.java, a file called Hello.class is created from the file Hello.java. We need to create a Car.class to be able to use this new and exciting class in our programs.

[nurmes]btg: javac Car.java
[nurmes]btg: ls
Car.class    Car.java     Desktop      Hello.class  Hello.java   
[nurmes]btg: 

Notice that Car.java doesn't contain public static void main(String[] args). We only need to have this main method in the class we use to run the program (by typing java Hello). So what are we going to put in our new class? Well, classes can have their own variables, called fields. Let's give our car a colour:


class Car {
	String colour;
}

What this means is that each car we create has a string which belongs to it, which describes its colour. Now for this car to be any use, we need to actually create one. So far all we've done is define the class - in other words, we have a design but we haven't actually tried to build one yet. Let's use the other Java file to make a car.


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");

		Car myCar;
	}
}

We now have a variable of type Car called myCar. Remember what we learned with strings - this is only a reference to a Car object. So, as with strings, we need to put something into it. This part is new - literally, we have to use the keyword new to create an actual Car object.


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");

		Car myCar = new Car();
	}
}

We've now actually built a car to the design (class) we came up with. We call this an instance of the Car class - a particular car made to the design. Notice we write new, then the name of the class (Car), then some empty brackets.

You might think this looks like calling a method, and you'd be right. The only difference is that this returns a new instance of the Car class. This special type of method is called a constructor, because it constructs an instance of the class. Later we will pass some parameters to the constructor inbetween the round brackets (just as we did with methods earlier).

Have another read over that section, slowly to take in the jargon and what it all means. Once you have that straight, we can paint the car:


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");

		Car myCar = new Car();
		myCar.colour = "Red";
	}
}

Look back at the file Car.java. Remember that we gave it a String variable (or field) called colour. I said that this variable belongs to each instance of the Car class. So when we access it, we can't just write colour. We have to say which car we want to paint, by writing myCar.colour. This says "the colour of the car in the variable myCar".

We use the dot in this way whenever we want to access a field belonging to an object. You'll see it a lot more. Now we have painted the car, let's print out its colour:


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");

		Car myCar = new Car();
		myCar.colour = "Red";

		System.out.println(myCar.colour);
	}
}

Notice how we write myCar.colour again, just as if it were a normal variable. At this point it's probably worth trying to run the program - make sure both files are saved:

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
Hello, world!
Red
[nurmes]btg: 

It's interesting to note at this point that we haven't compiled the Car.java file since we added the line String colour;. So it shouldn't really have worked. However, when we compile Hello.java, the compiler checks all the other classes which are used by it, and compiles them too if necessary.

Anyway, regardless of all that, the car appears to have kept its colour. For practice, let's make another one:


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");

		Car myCar = new Car();
		myCar.colour = "Red";

		Car sportsCar = new Car();
		sportsCar.colour = "Racing green";

		System.out.println(myCar.colour);
		System.out.println(sportsCar.colour);
	}
}

 

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
Hello, world!
Red
Racing green
[nurmes]btg: 

Now suppose we can't afford two new cars, so we copy the red one to the other variable and hope no-one notices:


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");

		Car myCar = new Car();
		myCar.colour = "Red";

		Car sportsCar = myCar;

		System.out.println(myCar.colour);
		System.out.println(sportsCar.colour);
	}
}

 

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
Hello, world!
Red
Red
[nurmes]btg: 

Our scam appears to have worked... now let's paint the sports car green:


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");

		Car myCar = new Car();
		myCar.colour = "Red";

		Car sportsCar = myCar;

		System.out.println(myCar.colour);
		System.out.println(sportsCar.colour);

		sportsCar.colour = "Racing green";

		System.out.println(myCar.colour);
		System.out.println(sportsCar.colour);
	}
}

Uh oh, we'll be in trouble when the missus gets back...

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
Hello, world!
Red
Red
Racing green
Racing green
[nurmes]btg: 

In Java, as in real life, one car is still only one car, however many references to it you might have. Although there were two variables of type Car, there was only ever one actual Car object. So when we changed the colour of sportsCar, we actually changed the colour of the family car too, since they were both the same car in the first place. To have two different coloured cars we need to construct two, by writing new Car() twice.

This is an interesting point to refer back to the lesson on strings. Remember that I said strings are immutable (they can't be changed), so this sort of mess would never happen. Most objects (including our Car) aren't immutable, so we have to be careful that when we change an object, we're not changing it for someone else too.

Let's cut back our program a bit:


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");

		Car myCar = new Car();
		myCar.colour = "Red";

		System.out.println(myCar.colour);
	}
}

This is all fine:

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
Hello, world!
Red
[nurmes]btg: 

But what if we forget to construct any cars? As usual, let's try it and see:


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");

		Car myCar;
		myCar.colour = "Red";

		System.out.println(myCar.colour);
	}
}

 

[nurmes]btg: javac Hello.java
Hello.java:6: Variable myCar may not have been initialized.
                myCar.colour = "Red";
                ^
1 error
[nurmes]btg: 

The compiler doesn't seem to like our program any more. We're accessing the colour of the car in the myCar variable. Only trouble is, the variable doesn't actually contain a car. We haven't constructed one yet. Remember that the variable myCar should contain a reference to an instance of the car class.

So what on earth does it refer to, if not a car? Unfortunately, because of the message we just saw, I can't easily write a program to show you. What I can tell you is that the value of myCar will be null. This is the equivalent of a zero for object references. When we create a variable for any object type (String, Car, whatever), it starts off with the value null, so it doesn't refer to any object at all. We can test to see if a variable is null using ==. However if we try to write something like myCar.colour the compiler stops us - obviously null can't have a colour, if we don't construct a car then we can't ask what colour it is.

Before we go on, we should fix that mistake and make another car (forget about colours for now):


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");

		Car myCar = new Car();
		Car sportsCar = new Car();
	}
}

Now the variable colour is different for each car, and so it should be. But what if we had some variable we wanted to belong to all the cars, and have the same value for all of them? Like the model number? We could do this:


class Car {
	String colour;
	int model = 200;
}

 


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");

		Car myCar = new Car();
		Car sportsCar = new Car();

		System.out.println(myCar.model);
		System.out.println(sportsCar.model);
	}
}

 

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
200
200
[nurmes]btg: 

You can see this works, but what if we decide to change the model number to something a bit more funky? We would have to go and change it for every single car. Also, the value is stored once for each car - if there are a lot of cars this is a big waste of space. We can say that a variable exists only once, for all instances of a particular class, like this:


class Car {
	String colour;
	static int model = 200;
}

Now we don't even need to construct one car to change the model number, as I'll show you:


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");

		Car.model = 205;

		Car myCar = new Car();
		Car sportsCar = new Car();

		System.out.println(myCar.model);
		System.out.println(sportsCar.model);
	}
}

Notice that, instead of using the name of a Car variable, we've just used the name of the class (Car) before the dot. This only works with variables that are declared to be static, because they belong to the Car class in general, rather than any particular car.

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
205
205
[nurmes]btg: 

We can still change the model number after we've constructed one or more cars, and it still applies to all the cars:


class Hello {
	public static void main(String[] args) {
		System.out.println("Hello, world!");

		Car.model = 205;

		Car myCar = new Car();
		Car sportsCar = new Car();

		System.out.println(myCar.model);
		System.out.println(sportsCar.model);

		Car.model = 106;

		System.out.println(myCar.model);
		System.out.println(sportsCar.model);
	}
}

Note that unlike before, there are actually two separate cars here which can have different colours.

[nurmes]btg: javac Hello.java
[nurmes]btg: java Hello
205
205
106
106
[nurmes]btg: 

I think we both deserve a break now. There's more on objects in the next lesson, but a lot of the tricky stuff is out of the way. You know the drill - fill out the questionnaire, then move on.

But
what
do
you
think?
This lesson was...
What don't you understand? Other comments?
Excellent
OK
Poor
Your email (optional)
Go on to If You Don't Object...

Too patronising? Too complex? Typing error? Offended by traffic cones? Got a question or something I should add? Send an email to ben_golding@yahoo.co.uk !

visits to this site

The contents of this site are copyright of Ben Golding