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

Java Inheritance in Java Inheritance in Java Everything Inherits from Object

Rafał Stasiak
Rafał Stasiak
3,763 Points

Proper cast

Can someon guide me how should I cast properly this widged object?

public class Main {
    public static void main(String[] args) {
        Thing widget = new Widget();
        <need to cast widget object>.refuseToWork();
    }
}

class Widget extends Thing {
    String[] excuses = {"It's too heavy.", "I don't know how.", "You know I don't speak Spanish."};
    int excuseId = 1;

    void refuseToWork() {
        String excuse = excuses[++excuseId];
        System.out.println(excuse);
    }
}

class Thing {
    String purpose = "do stuff";

    void printPurpose() {
        System.out.println(purpose);
    }
}

1 Answer

Michael Hulet
Michael Hulet
47,913 Points

The right thing to do here probably isn't to cast it at all, but properly declare its type instead. Widget inherits from Thing, so it'd technically work if you cast it before calling refuseToWork, but you know when you create it that it's a Widget, so it's likely best to just declare its type as such

However, if you really wanna declare it as a Thing and cast it, you can do it in Java by writing its more specific type in front of its variable name when you reference it, like this:

((Widget) widget).refuseToWork();
Rafał Stasiak
Rafał Stasiak
3,763 Points

This is a little bit confusing.

As I understand when I use (cast) before refuseToWork() I prioritizing an object I want to run, but why I need to firstly point at class Widget, why can’t I simply declare (Widget).refuseToWork() ?

Secondly, if I would change this a little bit like below:

Object widgetExample = new Widget(); ((Widget)WidgetExample).refuseToWork();

would upper code work properly?

And at last, you mentioned "The right thing to do here probably isn't to cast it at all, but properly declare its type instead." How this code would looks like If I don’t want to cast is at all, but still run it properly as you mentioned?