Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Java Data Structures!
You have completed Java Data Structures!
Preview
Interfaces help define a contract that a class must adhere to. Let's learn how to sign those contracts.
Copy/Paste
Movie movie1 = new Movie("Spirit: Stallion of the Cimarron", "Family", LocalDate.of(2002, 5, 24));
Movie movie2 = new Movie("Life is Beautiful", "Comedy", LocalDate.of(1997, 12, 20));
Movie movie3 = new Movie("My Neighbor Totoro", "Fantasy", LocalDate.of(1988, 4, 16));
Resources
- Interfaces
- Implementing an interface
- java.lang.Comparable
- Access Control keywords - (Class code can see inside other instances of the same class because it is private to the class)
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
All right, welcome back.
0:02
We're going to jump straight
into this next
0:03
task here before I get carried away
explaining things without some context.
0:05
I'm going to move pretty quick,
but it's all things
0:09
we've covered in the prerequisites.
0:11
All right, let's go.
0:12
I'm going to add two new movies here.
0:14
The text for these
will be down in the teacher's notes,
0:16
so you won't need to type all this out
either.
0:18
So movie two is a recommendation
that Brian gave me.
0:21
Thank you, Brian.
0:24
And movie three was from Christian,
so thank you as well, Christian.
0:25
Now, don't judge me, everyone.
0:29
Can you believe I've never seen this one?
0:30
It came out 12 days after I was born, too.
0:32
I'm such a slacker.
0:35
While we're at it, let's
clean up a bit and move this local date.of
0:37
right into the first movie here,
since we're familiar with it now.
0:40
And let's rename it to movie one.
0:52
Cool.
0:55
So what I'm trying to do next is display
all of these so I can see my choices.
0:56
So an array and a loop
sounds logical, right?
1:00
Let's do that.
1:02
Let's say movie array
1:03
all movies equals movie
1:07
1, movie 2, and movie 3.
1:10
Sweet.
1:15
Nice array literal there.
1:15
Alright, let's loop over these movies.
1:17
Let's say for
1:19
movie, movie in all movies.
1:23
Okay, let's see.
1:31
Now this movie is referring
to the currently iterated over movie.
1:32
Convenient.
1:35
Whoops.
1:45
Looks
I forgot to delete that old date variable.
1:46
We'll get rid of that.
1:51
Save and try again.
1:54
Cool, so we're getting them printed out
beautifully.
2:03
Unfortunately, I'm terrible
at making decisions.
2:05
I would prefer to just watch these
from oldest to newest,
2:08
so by release date, right?
2:12
So let's try out that sort method
we used back in the arrays course.
2:13
We'll import java.util.arrays up top.
2:17
And let's add this
right in between our array declaration
2:22
and our loop,
so it's sorted before we print them out.
2:25
We'll say arrays.sort all movies.
2:28
Okay, let's save and try again.
2:34
Hmm, we got an error here.
2:37
Class cast exception.
2:43
Class Movie cannot be
cast to class Comparable.
2:45
What does that mean?
2:48
If you followed our arrays course, this
comparable should ring a few bells, right?
2:50
We were comparing strings
with the compareTo method,
2:54
and it was returning either
a negative 1, 0, or positive 1, remember?
2:56
Alright, so we need our movie class
to be able to be sorted by release date,
3:01
so that we get the oldest movies
first. As you saw in that error message,
3:06
it was complaining that the movie class
didn't implement the comparable interface.
3:10
So it was saying that the object
was not able to be compared.
3:15
And that makes sense, right?
3:19
In order for it to sort something,
you have to compare it to something else.
3:21
Does this one come before this one?
3:24
So let's learn about interfaces.
3:26
I think the easiest
3:29
way to imagine
an interface is to view it as a contract.
3:30
It is a contract that the programmer signs
when they add it
3:34
to a list of interfaces
that a class implements.
3:37
The programmer is guaranteeing
that the class can perform
3:40
all of the actions
as defined from the interface.
3:43
This contract is set in stone,
3:47
and if it is not held up,
the code will not even compile.
3:48
Now, one of the more powerful features
of interfaces is that they can be used
3:52
where you would define reference types,
so in a declaration or in a method,
3:56
and you can check if something
meets the contract by using instance of.
4:01
So let's go sign some contracts.
4:05
So implementing an interface is as simple
4:08
as using the implements keyword
and then the name of the interface.
4:11
So if we come into the class here,
we say implements comparable.
4:14
We've now signed the contract
by implementing the interface.
4:19
So now let's see what happens
if we try to compile this.
4:22
So we
4:30
get back movie is not abstract
and does not override an abstract method
4:30
compared to object in comparable.
4:34
Okay, so let's see if we can figure out
what we need to do
4:38
with that compareTo method.
4:41
So let's jump over to Google
and search for Java Comparable.
4:42
Okay, here we go.
4:49
So this is the interface documentation
for comparable.
4:50
And you'll notice that it's
using some syntax that we haven't quite
4:54
looked at yet.
4:56
So the method we need to look for here
is compareTo.
4:59
And it's using the syntax where it says T
and then O.
5:03
That's
the generic way of documenting things,
5:06
and we haven't quite gotten to that yet.
Don't worry.
5:09
So let's just do what the error said,
which was implement compare to.
5:11
So it says it compares this object
with the specified object for order.
5:15
It returns a negative integer, zero
or positive integer,
5:20
as the object is less than, equal to,
or greater than the specified object.
5:23
So just like before with the strings, right?
5:28
We compared apple to banana,
and since A comes before B,
5:30
we got a negative one back,
because it was considered less than.
5:33
Apples to apples
gave us a zero because it was equal.
5:37
And banana to apple gave us a positive one
because B is considered
5:40
greater than A with strings.
5:43
So you really only get three values.
5:45
It's negative one, zero, and one.
5:47
So what this is saying
is it's saying the implementer, that's us,
5:49
must ensure that if you compare X to Y,
5:53
that Y to X is the inverse of that, right?
5:56
So if I compare X to Y
and it says that's negative one,
6:00
when I compare y to x it better say
positive one so that I can sort
6:03
both ways for everything.
6:07
And it talks about
6:09
if it throws an exception
they'd both better throw the exception.
6:10
So this is difficult to read,
I know, but it's basically saying
6:14
we really need to ensure
that we covering all outcomes, right?
6:17
Here it's saying if x is greater than y,
and y is greater than z,
6:21
then x better be greater than z as well,
right?
6:25
This line here, it's strongly recommended
but not strictly required
6:28
that if x compared to y
is equal to 0, meaning
6:32
they're considered equal, then it should be
the same as x equals y.
6:35
One of the things that all objects have
is a dot equals method.
6:40
But basically what this is saying
is that if you're going to return 0,
6:44
you probably should make sure that x
is equal to y with that method as well.
6:47
So again,
and here o is the object to be compared.
6:52
So what's going
to happen is we're going to write a method
6:56
that's going to be on our class,
6:58
and we're going to compare it
to another movie instance.
6:59
One of the nice things on interfaces
7:03
is that it shows all of the places
where they've been implemented.
7:05
You can tell it's a lot.
7:08
So string implements comparable,
which is why
7:10
we were able to use arrays.sort
on the strings before.
7:12
Looky here, here's our local date.
7:16
Perfect.
7:18
So we now know that
we can compare local dates,
7:19
and we can use this to help sort
our movies.
7:22
So let's add
this compareTo method to our movie class.
7:24
Alright, so one thing you always want
to do is use the override annotation here.
7:29
There's not really an annotation
for implementing
7:33
like we're technically doing here,
so we use override.
7:36
It provides the same benefits
as overriding a method does.
7:39
So this is public,
7:42
and we want to return an int,
negative 1, 0, or 1, remember?
7:44
And we'll say compareTo, and we said that
we're just going to implement objects.
7:48
So we'll say compareTo object OBJ.
7:53
Okay, first things first, let's go ahead
7:57
and we'll cast to a movie,
so we can access all those movie values.
8:00
Let's name it other.
8:04
We received an object,
but in our example here,
8:06
we know it's a movie,
so we'll be safe here.
8:09
So, the documentation said,
if we're comparing a specific movie
8:12
instance to itself, it should return zero.
8:15
So let's go ahead and we'll call
the equals method on ourselves.
8:18
So we can simply write, if equals
the other, meaning is the other movie
8:22
equal to this movie instance
that's running this compareTo method,
8:27
then let's go ahead and get out of this
method and say it's zero.
8:31
This is checking if the
8:35
two references
point to the exact same object in memory.
8:36
So we'll know if they're equal now,
but we're using compareTo
8:40
to help with sorting,
so we need some more logic.
8:43
So here's a trick
that we likely haven't done yet.
8:46
You can have multiple return statements
in a single method.
8:49
This is handy for situations
just like we're encountering here.
8:52
If two objects are the same, or are equal,
8:56
there's no reason to keep going
with anything else in this method.
8:58
So let's just get out of here.
9:01
So this will say return 0.
9:02
And now, because this is an if statement,
this return is only going to happen
9:04
if it's true.
9:08
And if that does happen,
the rest of the code below won't run.
9:09
If this is false,
we're going to keep going.
9:12
All right,
9:15
we're looking to compare the two release
dates, which are of type local date.
9:15
And we saw local dates
implement the comparable interface.
9:19
So we can actually use compareTo on them
inside of our compareTo method.
9:22
It's like compareTo inception in here.
9:26
So we return the returned integer from
9:29
mReleaseDate and
9:31
that could be it
right? That could be the end of the method.
9:36
But what about the odd chance
that we ended up
9:39
getting two different movies
with the exact same release date?
9:41
This would return zero,
which would make it look they were equal,
9:44
even if they weren't.
9:48
So we can protect that case
with just a little bit of logic.
9:49
Let's store this comparison.
9:52
We'll say int DateComp,
9:57
for comparison, equals that.
9:59
If dateComp equals zero,
then we'll go ahead
10:02
and we'll make sure that the titles aren't
the same too.
10:04
The titles are strings,
so again, we can use compareTo on that.
10:08
And if they are the same, we're probably
talking about the same object.
10:11
Wait a second.
10:17
That mTitle field is private,
this one here.
10:19
How are we accessing that?
10:22
Well, it's private to the class, but we're
in the class, so we're able to see it.
10:24
So we have another instance here,
but we're inside the same class
10:29
so we can access that field.
That's pretty cool, right?
10:32
Okay, so we got that return in there,
and if it's not that,
10:36
then we're
just going to return the date comp.
10:39
All right, let's walk that one more time.
10:43
Okay, so we're going to come in
and we're going to cast it to other.
10:46
We're going to check
using the local method equals.
10:50
if it's equal to the other and equals
again
10:52
is on the object, we're going to say
let's not even think about anything else.
10:55
Let's just get out of here and return 0.
10:59
If they're not equal here, then
we're going to compare the creation dates.
11:02
If they happen to be exactly
the same date,
11:07
we better just make sure
and compare the title to the other title.
11:09
Now, if they're both 0,
11:14
then we'll return 0,
because they're definitely the same movie.
11:16
The compareTo method here will return zero
and will return that.
11:19
Otherwise, we're going to return
whatever happened here.
11:23
Make sense?
11:25
Now, this is definitely a place
where we should write a test.
11:27
In fact,
I feel almost ill not writing one.
11:30
And I hope that after we go through a unit
testing course,
11:32
I can cause you to have
the same feeling in your gut.
11:35
Okay, so now let's flip over to example.
11:38
So we already have the sorting code there,
so let's run
11:42
that.
11:44
Awesome!
11:52
They're in the right order.
11:52
If we look above, it started with Spirit,
Life is Beautiful,
11:55
then Totoro.
11:58
After sorting,
12:02
we got Totoro,
Life is Beautiful, and then Spirit.
12:03
Awesome! We got it. We're sorting.
12:06
And now we have a comparable movie.
12:08
Great job!
12:10
So now we know how to sign contracts
using interfaces.
12:12
The concept of being able to state
how you expect code to work unleashes
12:15
a lot of power.
12:19
We'll see this power very clearly
in the next stage as the collections
12:21
framework we'll be exploring
fully embraces this interface concept,
12:24
and it is a testament to how extensible
using them can make your tools.
12:28
The thing to remember is that interfaces
define
12:33
what your code must do, but it leaves the
how up to the implementer.
12:35
It is possible to have multiple interfaces
assigned to a class.
12:40
So let's see how to do that in
the next video, right after this exercise.
12:43
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up