In statically-typed object-oriented languages (like Java, C++, C#, ...), suppose I declare an abstract class:
public abstract class myclass1 { ................. }
Most of these languages (like Java) wouldn't allow us to create an Object of an Abstract class, but they do allow us create an Array of Object of an Abstract class. Like,
myclass1 arr[] = new myclass1[10];
We can create an array of 10 objects.
I have some confusion about how this kind of array works. How do I use this array? What is the actual use of this array in real-life projects? Any explanation with an example will be very useful.
Asked By : Abhishek Karmakar
Answered By : Wandering Logic
In statically-typed object oriented languages (like Java), you can not create an object of an abstract class. Abstract classes are (usually) not completely defined, so creating such an object wouldn't make any sense.
What you can create is a reference to an object instance of an abstract class. A reference is just a pointer to an object, not the object itself.
myclass1 arr[] = new myclass1[10];
Creates an array of 10 null
references to objects of class myclass1
.
Similarly
myclass1 x = null;
Creates a copy of the null
reference and casts it to a reference to a myclass1
.
You can always assign an object of a (non-abstract) subclass of myclass1
to a reference to myclass1
. So for example:
x = new ConcreteClass();
(where ConcreteClass
is a subclass of myclass1
).
Any element of arr
is also a reference to myclass1
. So:
arr[7] = new ConcreteClass();
Best Answer from StackOverflow
Question Source : http://cs.stackexchange.com/questions/46984
0 comments:
Post a Comment
Let us know your responses and feedback