Generally, when a new object is created in Java it follows the idiom:
Object obj = new Object();
where the Object()
constructor matches the object type Object
.
But what if it doesn't? I understand from the Oracle Docs on creating objects and polymorphism that the constructor must be in that object's class or one of its subclasses. However, suppose we wanted to declare a new stack. My first instinct would be:
Stack s1 = new Stack();
But I assume it's valid to do it this way, too:
Object s2 = new Stack(); //This
Is there a difference here? What are we really saying about s2
? I'm guessing s2
is simply an empty stack, but only has access to the Object
class methods? I'm not sure why someone would ever do this, but I want to solidify my understanding of the Java hierarchy. Are there really any circumstances where someone would use a subclass's constructor when creating a new object?
Any and all informative responses will be appreciated. Thanks in advance!