So I am confused about Declared vs Object types. For example:
Animal creature = new Mammal( new Vertebrate)
I know that the declared type is Animal, but what would the object type be? Mammal or Vertebrate?
Asked
Active
Viewed 447 times
0

BrownKid
- 11
- 1
-
2Your example is really bad, why would the `Mammal` constructor take a `Vertebrate` parameter? Not to mention your syntax is wrong there, so I suggest not coming up with your own examples. Read some good tutorials instead. – Kayaman Apr 28 '22 at 06:59
-
I am confused, the above isn't valid java syntax. Do you mean `Animal creature = new Mammal( new Vertebrate())`? If so, yes, it is Mammal. Note that the `new Vertebrate()` also creates a new object, but that is directly passed to the constructor of the Mammal class, that is all there is to this. – GhostCat Apr 28 '22 at 07:00
-
Does this answer your question? [Difference Between Object Type and Reference Type](https://stackoverflow.com/questions/16730109/difference-between-object-type-and-reference-type) – justanotherguy Apr 28 '22 at 07:03
2 Answers
1
Here's a thumb rule:
Declared type is whatever is on the left and side of the =
, while object type is whatever is after the new
keyword. In your case, declared type would be Animal
, whereas object type would be Mammal
. Vertebrae
does not play any role here apart from calling the parameterised ctor of Mammal class.
Thumb Definitions:
Object Type: Whatever class' ctor you use to instantiate an object
Declared Type: Whatever the storage class of the variable you declare to be

justanotherguy
- 399
- 5
- 16
0
As others have said Mammal, you can verify this by printing out .getClass()
public static void main(String[] args) {
Animal mammal = new Mammal(new Vertebrate());
Animal animal = new Animal();
System.out.println(mammal.getClass());
System.out.println(animal.getClass());
if (mammal instanceof Animal) {
System.out.println("mammal is animal");
}
if (mammal instanceof Mammal) {
System.out.println("mammal is mammal");
}
if (animal instanceof Animal) {
System.out.println("animal is animal");
}
if (animal instanceof Mammal) {
System.out.println("animal is mammal");
}
}
output:
class Scratch$Mammal
class Scratch$Animal
mammal is animal
mammal is mammal
animal is animal

Viktor Mellgren
- 4,318
- 3
- 42
- 75