Reputation: 25
I'm learning java and have a question about object types.
Take the following as an example:
class A { }
class B extends A { }
class C {A myObject = new B();}
What is the accepted way to describe the type of myObject?
Would you say it is Type A, Type B, or Type A and B?
Thanks.
Upvotes: 2
Views: 136
Reputation: 9247
myObject
is a reference of type A
(your variable is declared to be of type A
).
The object itself, which is referred to by myObject
, is of type B
. The instance is of type B
.
It’s a matter of context and focus.
When you use myObject
in other places you may not know it is an instance of class B
, only that it is of type A
.
Upvotes: 6
Reputation: 207006
Inheritance implies an "is a" relationship - an instance of a subclass is an instance of a superclass. In your example, since B extends A, an instance of B is also an instance of A - that's why you can assign a new B to a variable of type A without casting.
The variable myObject
is of type A, but it refers to an object which is really of type B.
Upvotes: 0
Reputation: 346536
myObject
is field with the declared compile-time type A. At runtime, it will refer to an object of type B.
This distinction between the declared (or compile-time) type of variables and the runtime type of objects is crucial to understanding how polymorphism works in a statically typed language like Java. Some things (like the invocation of overriden methods) are determined by the runtime type, othersy (like the invocation of overloaded or static methods) by the compile-time type.
In general: the declared type determines what you can do with the object, while the runtime type determines how it will behave.
Upvotes: 1
Reputation: 28703
It is of type A, since type means operations you can do with it, but it is an instance of B, so all the operations you do will be in B-manner.
Upvotes: 1