Instance Variable - Intro to Java Programming

Sharing buttons:

You've just practiced with Sara how to find the public interface of another

class, now let's go back to our car class. We had discovered the public

interface that you see over here and now our goal is to implement it. So

imagine a car object and let's have a look at the add gas method. We're adding

a certain amount of gas and what should that do to the car. Well, remember,

it's not a real car and it's not real gas. This car is just an object in a

computer, and it remembers some information. In particular, in order to add

gas, the car needs to remember how much gas it has. In Java, you use variables

to remember anything. And here's is how you write such a variable, a variable

has a name just like the variables that you've seen in the previous lesson as

well as a type. And then there is this key word private here that simply means

that the variables of an object are a part of the private implementation. The

programmer who uses the public interface doesn't need to know about that. You

will always want to declare instance variables as private. Let me tell you why

they're called instance variables. Let's have a look at another car object, or

as we say, another instance of the car class. Of course, it also needs to

remember how much gas it has. And the amount of gas that this object has will

be different from the amount of gas of the other object. So each of these

objects, or each of these instances of the car class needs to have its own

variable to store that information. That's what it means to be an instance

variable. It's a variable that occurs in every instance of the class. Now

there's another thing that each car object should remember, namely its mileage.

Here's how you can define the variable, we give it a name, miles driven. It's

type, it's again a number. And once again, each instance of the car class has

its own value, so it needs its own copy of that variable. These are the two

instance variables that we need for the car class. You will soon see how the

methods of the car class update or read those instance variables. But first, go

ahead and practice with Sarah how to discover the instance variables that we

need for the person class.