Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Arthur Podkowiak
3,633 PointsTrouble understanding type casting and interfaces from Java Data Structures course
I'm having a lot of trouble understanding how to use type casting and when to use it. In the java data structures course, we went over it and it seems to me that basically you change a class to hold not only its own methods and fields, but also the ones of a parent or child class. Is this correct? I am wondering if someone can explain in the most simple terms how some of my code works? I am going to past some of the code written from Java Data Structures course focusing on type casting and interfaces when writing the "Treet" program. I'm wondering if anyone can kind of go through what I paste if they did those courses? Any help is much appreciated!
@Override
public int compareTo(Object obj) {
Treet other = (Treet) obj;
if (equals(other)) {
return 0;
}
int dateCmp = mCreationDate.compareTo(other.mCreationDate);
if (dateCmp == 0) {
return mDescription.compareTo(other.mDescription);
}
return dateCmp;
}
and we use this code to help sort our Treets by their creation date using:
Treet[] treets = {secondTreet, treet};
Arrays.sort(treets);
for (Treet exampleTreet : treets) {
System.out.println(exampleTreet);
So in here I know we are first overriding the .compareTo method that is in the Object class because it compares just letters or numbers or whatnot. So in this method we are making a new way to compare by using @Override to compare the creation date, correct?
After that, we start our method that creates an integer object from the "Object" class called "obj". We are going to compare things within this method to obj, correct? In the method we declare a new instance of Treet called "other" which we type cast obj as well to the Treet class. This is where I get confused. Is other taking methods from obj? Or is obj now becoming a part of the Treet class so we can use those methods on it?
The next lines are just comparing 'obj' to 'other'. I have no idea how they compare them because we don't compare their creation dates here! It literally just states to compare them, so I'm guessing the "Treets" would have to be identical in what they say (hopefully people reading this have done the course so they know what I mean). After that, we create a new variable 'dateCmp' which will store the .compareTo's output (-1, 0, or 1) after comparing the creation date to 'other''s creation date. How come we compare the private variable mCreationDate to 'other''s creation date? When does 'other' even receive a creation date if it is not defined anywhere else in our code?
Anyways, moving on, I would love if someone can explain this whole part of the code to me. When I type it out it seems so jumbled and makes no sense.
The other part of the code also confuses me since it is in the Example.java file and part of the Example class. I never mentions running the compareTo code so I'm not sure how it knows to output the Treets in order of their creation date. How does this happen! Java is so confusing, someone help me! For reference, I will post the entire code at the end of this post. Sorry for its length!
Example.java code:
import java.util.Arrays;
import java.util.Date;
import com.teamtreehouse.Treet;
public class Example {
public static void main(String[] args) {
Treet treet = new Treet(
"arthurpodkowiak",
"Want to be famous?",
new Date(1421849732000L)
);
Treet secondTreet = new Treet(
"journeytocode",
"@treehouse makes learning Java sooooo fun! #treet",
new Date(1421878747000L)
);
System.out.printf("This is a new Treet: %s %n", treet);
System.out.println("The words are:");
for (String word: treet.getWords()) {
System.out.println(word);
}
Treet[] treets = {secondTreet, treet};
Arrays.sort(treets);
for (Treet exampleTreet : treets) {
System.out.println(exampleTreet);
}
}
}
Treet.java code:
package com.teamtreehouse;
import java.util.Date;
public class Treet implements Comparable {
private String mAuthor;
private String mDescription;
private Date mCreationDate;
public Treet(String author, String description, Date creationDate) {
mAuthor = author;
mDescription = description;
mCreationDate = creationDate;
}
@Override
public String toString() {
return String.format("Treet: \"%s\" by %s on %s",
mDescription, mAuthor, mCreationDate);
}
@Override
public int compareTo(Object obj) {
Treet other = (Treet) obj;
if (equals(other)) {
return 0;
}
int dateCmp = mCreationDate.compareTo(other.mCreationDate);
if (dateCmp == 0) {
return mDescription.compareTo(other.mDescription);
}
return dateCmp;
}
public String getAuthor() {
return mAuthor;
}
public String getDescription() {
return mDescription;
}
public Date getCreationDate() {
return mCreationDate;
}
public String[] getWords() {
return mDescription.toLowerCase().split("[^\\w#@']");
}
}
Edit: I just looked at the code again and do realize that we can use compareTo because we implemented the Comparables into Treet class. Does this mean that every treet instance created will undergo any Comparables code automatically? how does the Example code know how to sort what was compared? We don't tell it to sort by creation date, we're just comparing in the Treet class so I don't understand how it can work. Also, since we are comparing two instances of Treets, will it compare multiple ones? Do they all go through the process every time a Treet is created? I'm guessing no since our array for Treets only spans 2 lengths so it only compares how many we have in there, correct?
3 Answers

J.D. Sandifer
18,813 PointsIt look's like you're essentially asking two main questions: What is type casting? and How do things get sorted - e.g. what does compareTo do, etc.? Let's look at them separately:
Type casting: This is about Inheritance. A real world example is bicycles. If you have a mountain bike, you could refer to it as a mountain bike (it's class), but you could also just call it a bike (it's super-class). It's both. If you're just riding around the block and any bike will do, your mountain bike will work even though it's designed for a more specific task.
Now in Java, you might have a function written that deals with a more general class like bike. Since a mountain bike is a type of bike, it should be able to be used in that function, but we have to tell the compiler that. It looks something like this:
Bike newBike = (Bike) mountainBike; // where mountainBike is a MountainBike object we created earlier
Any time you see type casting, this is what is happening - a more specific object (subclass) is being used in a place where a parent class would be used.
Sorting: Java has classes that have built in sorting like TreeSet. They keep the data they contain sorted by comparing objects as they are placed in the set and placing them in a sorted order. Similarly, there are built-in functions that do this when called like Array.sort().
Each of these do the sorting by calling a compareTo() method on the objects being sorted. All Comparable objects have this method - either the general parent method or a version that overrides it. So that method is being used behind-the-scenes to sort objects. That's why we override it in our code - so the objects get sorted correctly behind-the-scenes.

Arthur Podkowiak
3,633 PointsHi J.D.,
Doesn't this line here type cast an object in the Object class to the Treet class?
@Override
public int compareTo(Object obj) {
Treet other = (Treet) obj;
I'm not sure which video this was, I know it's near the end of the second course in Java Data Structures though, one of the last 2 videos probably. Let me know your thoughts, thanks!

J.D. Sandifer
18,813 PointsYou're right, it does cast that way, however we know that the object coming in is a Treet in this case. It's just we have to have the same method signature for the compareTo() method if we want to override it so we have to except an Object rather than a Treet.
Remember, an object can (and must) work in place of any of it's parent objects. Even like this:
Object object = new Treet(); // Works since Treet is a subclass of Object - the default when none is specified
Of course, the compareTo() method will only be called when we're comparing another object of the same type - in this case a Treet. So we know this will work.
This is a good point. Perhaps casting works anytime we know we can count on the object being what we want. There's probably more to learn here because the variable side of the assignment is an object reference. It has to be a reference of the same type as the object it references, but it seems like it has some flexibility both up and down the chain of inheritance via casting...

Arthur Podkowiak
3,633 PointsYeah, there's definitely a lot to explore here. Luckily generics take some of this away so I've been trying to use that more effectively, I just wanted to make sure I understand everything I'm learning so I don't have to constantly look back at it later. Thanks for all your help!
Arthur Podkowiak
3,633 PointsArthur Podkowiak
3,633 PointsJ.D. this was an awesome explanation! Pertaining to typecasting, do we sometimes type cast from parent to a subclass? Or it's just most commonly used for specific class to a parent class? Because in the Treet program we wrote in the java course, we type cast an object created in the Objects class into our Treet class. Object is the parent class here and yet we are typecasting it into the Treet class. Why not just make another Treet object?
For sorting this makes a lot of sense. This also helps explain
@Override
a lot better. So when you override a method, it essentially overrides it for the entire program? Or just for that class? Because in ourExample
class we are sorting objects from the Treet class, which is where the method was overridden, but if we had another class and compared objects in that class, it would sort them the normal way with the defaultcompareTo
method, correct?J.D. Sandifer
18,813 PointsJ.D. Sandifer
18,813 PointsArthur, I may not fully understand type casting - I didn't think you could cast a parent class to a subclass. Or maybe that only works in certain circumstances?
Can you post a link to remind me where we did that with the Treet class? Which video was it?
And the sorting method is per class - each class (that can be compared) has it's own version of the same method. When you override the method, you're creating a version specific to the class where you're writing it. You're just telling the compile: don't use the parent class' version of
compareTo()
, I've got a special version for this class...