In the first lesson for classes, we talked about how we could create our own Java
types.
That's awesome, but if we modeled a duck, we need a way to define more information
about our duck.
We might want to store the name of the duck, the color, or how much it weighs.
We might even want to give our duck the ability to quack. Ducks quack right?
We want an amazing duck! Let’s take a look at how you would add Java class methods and
variables to our duck.
In this lesson we'll look at how to define and use attributes in your Java classes. 11 00:00:32,590 --> 00:00:36,489 These attributes can belong to either the class or the object,
so we'll discus what that means and how you define it. We'll also introduce behavior
using the new concept called methods,
and we're going to revisit static final
to get a better understanding with that means. By the end
you should know how to create Java class methods and variables,
and have our Duck class quacking!
Last lesson we left off with a Duck class,
and the ability to create Ducks. Unfortunately
our duck didn't do much. We couldn't even tell if it was a brown duck, or an orange duck.
We just knew it was a duck. When we're designing applications, we often
represent classes with a picture called
a class diagram. We use a box
with the class name at the top. We'll use this as we add functionality to our
class.
To give a class attributes, we define variables
inside the scope of the class. You can think of attributes
as adjectives for your class. They
describe the state of your class. Attributes are listed like this in a
class diagram.
We separate the name and the type with a colon. This isn't Java syntax,
that's because class diagrams can apply to any
object-oriented programming language. In Java code
attributes are declared right after the class declaration like this.
It’s just the data type, followed by the variable name.
This is the same as we saw in the variables lesson.
Now it's tempting to add everything you can think of as an attribute,
but in reality you only want to define Java class attributes that make sense
for your program.
You don't want to create attributes you will never use.
Remember, each attribute uses a tiny piece of memory.
That adds up when you have millions of ducks. It also provides more places where
code can break.
So only add what you
need.
You can also use other classes as attributes.
For example you might create a class called DuckTeam.
It contains a list of Ducks and the team name [sic - lead duck].
We'll look at this in depth in the next lesson, but I wanted to give you a taste
of the power you have
with classes.
The code for setting the value uses something called the "dot operator".
It’s called a dot operator because it uses a dot between the class variable
and the attribute variable. The dot operator just allows you to access the individual
attributes a class.
So if we wanted to set the weight of a individual duck, we'd set it like this.
If you're inside your class, the instance name is optional.
It's important to have a valid object when you try to
access an attribute. Otherwise you'll get the infamous
NullPointerException. You know what null is.
That's the value a class has when it's not assigned a value.
Since there's no class assigned yet, it doesn't know which attribute
to set. Let's make this all clear and look at it in code.
The first thing I'd like to show you is
how we'd update our Duck class. Right now we don't have any attributes.
Let's add the attributes we had in the class model. That was color,
We add those like this. Notice
they are declared the same way we declared variables in the variables lesson.
It's just type, then variable name. So that's our Duck class.
Let's instantiate a Duck in the main method of our application class.
From the last lesson, we just instantiated the class like this.
If we printed out all the variables, they'd all be zero.
We need to give them values.
To assign a value to the attributes of our object,
we use the dot operator like this. Now each has a value.
We use the dot operator when we're printing them out too. We run it,
and there's the values we set in code. Now our application class
So we can add attributes here too.
Let's create an attribute called my favorite number.
We can even assign it when we declare it. When we use a variable inside the class
it belongs to,
we don't need to use the dot operator. We can just use the name.
Now when we print it out in our main method, something interesting happens.
It won't let us compile. It gives the error,
non static variable cannot be accessed from a static context.
So what does that mean? All of these attributes belong to the class,
but are instance variables. That means each
instance or object of your class has it's own values for each attribute.
That makes sense when you're talking about the weight of a duck.
Of course each duck has its own weight. But what if you wanted to keep a count
of all ducks created? A variable like that
would not make sense in an object. Every object would have a copy.
Updating the count value in every duck
could become quite onerous. There's a way though
to attach a attribute to the entire class. To do this,
you define the attribute with the keyword static.
Instance variables are the default, and have no keyword.
Class variables require the static keyword. We'd add our
duckCount variable to the class, and it is available to every duck
object. However it's stored only once in memory.
This attribute is called a static variable.
The value belongs to the class, not an object.
If you change it, you change it for all objects.
To represent it in our class diagram, we underline static variables.
We also usually call it
with the class name in front like this. You can call a static variable using
the instance variable name, but that is really confusing to other developers.
It's not clear this is a static variable. So
by convention,
always use the class name like this. The other use for static variables are
constants,
If you remember in the variables lesson, we used the keywords
static final. Now you have a better idea what these keywords mean.
"static" means it belongs to the class, and "final" means
it never changes once it's set. So a "static final" variable
is a single constant value. This might make more sense by showing you the code.
In our Duck class we have three instance variables.
These are the ones that get copied for every object.
Let's create a static variable. We'll create the count variable.
So we write "static
long count". That
makes this variable a class variable. There is only one count for all
instances. Create a million ducks, and you'll only have one.
To show the difference, I'll create a second duck, and I'll initialize the second duck with
different values.
We'll set count equal to 1 when we create the first duck,
and then set it to 2 when we create the second duck. Notice
I use the class name when I'm referencing the count. This is by convention.
It makes the code easier to read, but we could also change it to be the instance
variable.
Before I run it, I'll use the instance variable.
I'm doing this because I want to show you that count is the same variable for both
objects. This isn't what you'd do in normal code though. You would normally use
the class name. Let's run it and see what it prints. As you can see the instance
values for each duck
are as we defined them, but the count is 2 in both cases.
The reason is we set count to 1, and then before we printed it,
When we tried to create a myFavoriteNumber variable on our application
earlier,
it gave us the non static variable error. That was because we never created an
instance
of our application class. The myFavoriteNumber was an instance variable.
If we add static to our definition, it will work.
And it does.
The next thing I promised was to make our duck quack. A really cool characteristic
Java classes
is we can assign behavior. Our classes get behavior
with Java methods. A Java method is a special Java block
inside a Java class that can return a value.
We also have the ability to send parameters to our methods.
If classes are nouns, and attributes are adjectives,
then methods are your verbs. These are the things your class can do.
Methods are responsible for changing the state
of your class or program. A method has a return type,
name, parameter list, and the block of code to run. The return type in this example is
the keyword void. Void is another special word that means
nothing. When you declare a method with a return type of
void, that means it doesn't have a return value.
We'll add the methods under the attributes.
Methods always are in the second section of the class diagram box,
they include the return type, and attribute list. When we execute a method,
we often say we are "calling" the method.
This is how we call the method in Java. It's the variable with the dot operator
again,
again, but in this case we also list the parameters inside
parentheses - even if the parameter list is empty.
In our duck example, let's create a method called quack.
It prints quack. Ok.
That's pretty boring, but that's what ducks say.(*) One thing to note here,
println is a method on out, which is a parameter
on system. When you have objects as your attributes in your class,
you can use the dot operator to drill down into the attributes
of the contained class. Let's create a more interesting method.
Let's create a method that changes the weight of our duck. In this case
we send the newWeight as a parameter to our method. The method still returns nothing,
but we are passing input variables into our method.
We declare parameters the same way we declare variables. Inside
we change the weight attribute to the weight parameter
passed in. To get the weight back
out of our class, we would introduce a method that can output a value.
So let's define getWeight. In this case
our return variable is not null. It's double, just like the weight we defined
earlier. We have no parameters in this case, so we use two
To return a variable, we use the keyword “return”.
The value it returns must be the same type declared in the method signature.
When we define a method that returns a value, it must
always return a value. Java throws an error otherwise.
This also means every path through your code must return a variable.
If there is a path through your code that
doesn't return a value, Java will complain. Let's play with this in code.
To demonstrate methods we're going to create getters and setters for our Duck.
These will get and set the weight. There are many reasons why you should use getters
and setters to access attributes.
We're not quite ready discuss that, but the general idea
is we can separate the attribute from the behavior of getting and setting the
attribute. We'll cover it more when we discuss
access modifiers. Right now, just know it's a good thing to do.
First we'll create a setter. This will set the value of our
duck weight. Since this variable is used inside the class, we do not use the
instance name.
There really isn't an instance name to use here. We assign weight
to newWeight. One of the benefits of creating getters and setters
is we can do other things when we set the value. You only want to do things that
make sense for these methods. Any additional action should be related to
the setting of the weight.
I'm going to print out a message that the weight was set.
Next we'll create the getter. This will return our duck
The difference in this method is we have a return value,
double, and we return a value. Nothing is passed into the method.
We'll add a message to print out here too. Now we'll use our new methods in the
main application class.
We run it, and not only does it print the correct values,
we can see the messages we added in our getters and setters.
For methods that return a value, all paths in the code must return a value.
For example let's put a conditional in the getter. We'll say
if our weight is greater than 20, we won't return a weight.
Now it won't compile. That's because if the weight is greater than 20,
this method has no return value. It's easy to see here
in this simple code, but if you have a more complex method,
it can be hard to find a missing return. Lesson learned,
keep your methods simple. The last thing to do is similar to what we did with
myFavoriteVariable. We're going to create a second method on our application
class.
We'll call it sayHello(). When we try to call it in our main method,
we get an error again. Non static method
cannot be referenced from a static context. It's the same problem we had with
myFavoriteNumber.
The method belongs to the instance of the class. We're trying to call it from the
class.
One way to solve this problem is to create an instance of the application class.
Then we can use the object to call the method. We just saw that methods apply
to the
instance of the class. What if we wanted a method that belonged to the class?
We saw this eariler with our attributes. If we want a class method instead of an
instance method,
we use the static keyword again. A static method applies to the class as a whole,
not the instances. It also means a static method cannot access
instance attributes. That's why we got an exception when we tried
accessing an instance variable from the main method. The main method is static.
It can only access
Again we always use the class name in front of the method name
when we call static method. Let's go check this out
in code. We had our sayHello() method eariler.
The way we got it to run, was to create an instance to call it from.
The other way is to make the method static. That's what we did
with myFavoriteNumber earlier. We can make the method static,
then call it using the class.
Note that you cannot access instance
variables from a static method. Our main method is static. The reason for that is
you need a place for your application to start, and there are no objects in
existence yet.
So main is static. That means you cannot access
instance variables in your main method until you create an object.
Okay that was a big lesson!
Feel free to watch it again. In this lesson we learned how to add Java class
methods and variables. We looked at how we can define our methods
and variables to be part of the instance or class using the keyword "static".
We revisited "static final" from the variables lesson,
and we now have a better understanding why "static final"
creates constants in Java. If you have any questions,
please leave them on DeegeU.com or in the comments below.
Hey! Thanks for watching the video.
There is a quick quiz for this on DeegeU.com if you'd like to gauge how much you've
learned.
If you like the videos you are seeing, please let me know by liking the video and
hitting the subscribe button for the DeegeU channel on YouTube. I'd really appreciate
that!
If you have concerns or questions please leave them in the comments below, or on DeegeU.com
There's a poll on the front page of DeegeU.com so
you can also let me know what topic is covered next. Thanks for watching and see you
in the next video!