When you execute SList s = new TailList();
, what happens is the following:
new TailList()
is invoked, creating a new object which the constructor ofTailList
is run for. When the constructor finishes, an anonymousTailList
reference is returned.- The anonymous
TailList
reference is assigned tos
.
Since a TailList
is inheriting from SList
, you can also refer to it by that. The reference to the object doesn't change the object itself.
Imagine I put a trash bin somewhere, and then tell someone who doesn't know of that object being a trash bin that I put a "container" at that location. The trash bin is indeed a container, but that person only knows that it's a container. This doesn't change the fact that it's a trash bin, but the other person can't safely assume that he can put trash in there, or that it is scheduled to be emptied at any time, therefore he wouldn't know to invoke this functionality on the "container" that he is refering to.
So for instance, let's say we have the following code:
String s = "Hello there";
Object o = s;
o
is now refering to a String object, but is treating it as an "object", it doesn't know that it has a length, or that it contains characters, even though it does.
s
on the other hand, while still refering to the same object that o
is refering to, knows that this object is a String
, and can use String
functionality on that object.
If we wanted to, we could assume that o
is a String
by a mechanism called "casting":
String s2 = (String)o;
We now refer to the object referenced by o
as a String
. All of this changes nothing for the object itself, it's all a mere change in reference. As if, for the previous analogy, the person who was told about the mysterious "container", will assume that the container is more specifically a "trash bin". We could also make a wrong assumption, that the container is a packaging container
Integer i = (Integer)o; // throws ClassCastException
Fortunately, when we assume wrongly in Java, we get a ClassCastException
, unlike in real life where if you put your items into a trash bin while refering to it as a packaging container your belongings will be thrown to garbage.
Or perhaps, what is confusing you is that first assignment. Well, new TailList()
part of SList s = new TailList();
by itself is a static invocation of the constructor of TailList
, and it will always return a TailList
reference. The assignment that comes afterwards will still refer to the TailList
object that was constructed by the invocation.
TL;DR
Yes, it's the same thing.