I understand that when creating a new object such as this:
GeomObject tri = new Triangle();
is more general and allows for more resuability
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.