Declared types and Actual types

后端 未结 1 1689
清酒与你
清酒与你 2021-01-15 17:14

I understand that when creating a new object such as this:

GeomObject tri = new Triangle();

is more general and allows for more resuability

1条回答
  •  有刺的猬
    2021-01-15 17:39

    Since Triangle is a subclass of GeomObject, isn't tri still a GeomObject?

    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:

    • What does it mean to "program to an interface"?

    I thought that n2.compareTo(n1) would work because it would call Object#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);
    
    • The variable type will be Object, no matter if you initialize it as Integer or another class e.g. String.
    • Only the overridden methods will behave as defined in the object reference run time type, this means if your 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.
    • The link provided above: What does it mean to "program to an interface"? explains the benefits of using an interface (or abstract class or a generic class) to generalize the work through generic interfaces/classes instead of direct implementation. Note that there are cases where this approach won't apply e.g. your current example using 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.

    0 讨论(0)
提交回复
热议问题