Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Unit Testing in Java Why Test? Code Reuse

Asif Ahmed
Asif Ahmed
2,881 Points

Declaring a variable and initializing it to a different type

In this video, we declare items as a BlockingQueue but then initialize it as an ArrayBlockingQueue. What's happening here? When is this valid? How specific do we need to be when declaring a variable if we will later initialize it to a later object?

private BlockingQueue<Item> items;
public Bin(int maxItems) {
    items = new ArrayBlockingQueue<>(maxItems);
}

1 Answer

BlockingQueue is an interface. ArrayBlockingQueue is a class that implements BlockingQueue. In Java, we can't make an instance directly from an interface (BlockingQueue items = new BlockingQueue(); is not valid). We don't necessarily care which implementation of BlockingQueue we use, but we want to be able to call the methods that BlockingQueue promises will be implemented in anything that implements BlockingQueue.

Suppose you have a made-up class named SomeClass which extends a made-up class SuperclassOfSomeClass and implements a made-up interface InterfaceSomeClassImplements.

We can use the same format when we have SuperclassOfSomeClass instanceName = new SomeClass(); or InterfaceSomeClassImplements instanceName = new SomeClass();.

We do not need to be very specific when declaring a variable, but it is often a good idea to make your code as clear as you can. You could do Object instanceName = new SomeClass(); since all classes inherit from Object, but you would need to cast instanceName to the class SomeClass if you want to use methods from SomeClass.