If a class is declared with a generic type parameter, and it's instantiated without specifying the type, does it default to Object?

generics, java, linked-list, object, queue

Solution

Yes, if you don't specify a type, it defaults to `Object`. But you should avoid using raw types and should use Generics as much as possible, because Generics provide tighter type checks at compile time.

You must know that the type parameter(s) are preserved only until Runtime, i.e. at Runtime type parameters are erased and this process is called Type Erasure.

Problem

I've seen quite a few questions about whether or not it's possible to specify a default type if one isn't specified. The answer to that appears to be no. My question is, if your class header expects a type parameter, and you simply don't pass it one, what does it default to? Object? Take a simple Linked Node implementation of a Queue (abbreviated): ``` public class ListQueue<T> implements Queue<T> { private Node<T> first; private Node<T> last; public void enqueue(T item) { Node<T> x = new Node<T>(item); if (isEmpty()) { first = x; last = x; } else { last.next = x; last = x; } } public T dequeue() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } T item = first.data; first = first.next; if (isEmpty()) { last = null; } return item; } } public class Node<T> { public T data; public Node<T> next; public Node(T data) { this(data, null); } public Node(T data, Node<T> n) { this.data = data; next = n; } } ``` Then in my test driver, I am seemingly able to enqueue/dequeue any type of data: ``` public static void main(String[] args) { ListQueue myQueue = new ListQueue(); // key point: no type specified myQueue.enqueue("test"); myQueue.enqueue(2); myQueue.enqueue(new Date()); System.out.println(myQueue.dequeue()); // prints "test" int result = 2 + (Integer)myQueue.dequeue(); System.out.println(result); // prints 4 Date now = (Date)myQueue.dequeue(); System.out.println(now); // prints current date } ``` Of course I have to cast everything which defeats the purpose of generics, but is it really defaulting my data items to Objects to allow them all onto the queue? That's the only explanation I can think of, but I'd like to confirm that since I can't find it concretely written out that that's the case.

Original source