Reputation: 1069
I understand that when creating a new object such as this:
GeomObject tri = new Triangle();
is more general and allows for more resuability, but what happens when tri is created like this:
Triangle tri = new Triangle();
Since Triangle is a subclass of GeomObject, isn't tri still a GeomObject? How does the declared type affect compilation? Thanks
*add: An additional question: say I have
Integer n1 = new Integer(3);
Object n2 = new Integer(4);
System.out.println(n1.compareTo(n2));
I tried this out on Eclipse and I got errors even if I reversed n1 with n2. I thought that n2.compareTo(n1) would work because it would call the Object compareTo method and since Integer is an instance of object, it would be passable, but this is not the case. Could you explain this?
Upvotes: 4
Views: 6993
Reputation: 85779
Since
Triangle
is a subclass ofGeomObject
, isn'ttri
still aGeomObject
?
Yes it is. Use the instanceof
operator to test this:
System.out.println( (tri instanceof Triangl) ); //prints true
System.out.println( (tri instanceof GeomObject) ); //prints true
System.out.println( (tri instanceof Object) ); //prints true because every class extends from Object
How does the declared type affect compilation?
It won't affect in any matter, just will make your code inflexible in case you need to use another implementation of GeomObject
that is not a Triangle
.
More info:
I thought that
n2.compareTo(n1)
would work because it would callObject#compareTo
method
This is incorrect since Object
class doesn't have a compareTo
method.
On the other hand, n1.compareTo(n2)
won't work since you're passing an Object
to the compareTo
method when Integer#compareTo
receives another Integer
class type.
Note that when declaring this:
Object n2 = new Integer(4);
Object
, no matter if you initialize it as Integer
or another class e.g. String
.n2
variable holds an Integer
, only the methods overridden in class Integer
from class Object
will behave as defined in the Integer
class, all the other methods, fields, even the variable itself will behave as Object
. In case of Integer
class, these methods are equals
, hashCode
and toString
.Object
when you should use Integer
. Note that Object
class is way too generic (at least for this case), so I won't recommend using Object
directly at least that you understand what you're really doing.Upvotes: 11