Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Abstract class quandary  RSS feed

 
Brandt Charles
Ranch Hand
Posts: 57
Chrome IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an abstract class Shape, which will be extended by two other classes Circle and Square. I am to create an array of data type Shape that will hold objects of class Square and Circle. Arrays are objects, but how is it possible to make one of a data type that cannot be instantiated (because the class is abstract)? Can someone please shed some light on this?

And as always, my sig says it all, so please be gentle.

Thanks in advance.

Brandt
 
Rusty Shackleford
Ranch Hand
Posts: 490
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is true an abstract class can not be instantiated, but its non-abstract children can.

Shape circle = new Circle()

or

Circle circle = new Circle()

Both create a Circle object that extends shape. The former is generally considered better(but has its issues), but the second one is also valid. Of course, since you are creating an array of them, you do not need names for the references.

The first is better because it allows for more flexible code, but if a method in Circle is not defined in Shape it is not directly accessible.

The second way is less flexible but every variable and method in both classes are easily accessible.
[ June 28, 2006: Message edited by: Rusty Shackleford ]
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
also, think of it this way... the line

Circle myCircle = new Circle();

creates two things. it creates a Circle object, and it creates a REFERENCE that points to a Circle. in this case, that reference is named myCircle.

in Rusty's example:

Shape circle = new Circle()

you are here creating a Circle object, and a REFERENCE variable, named circle, that refers to a Shape. since a Circle IS-A Shape, everything is ok.

your array is NOT an array of Shapes, but an array of REFERENCES to a Shape. it doesn't matter what the final type of that object is, as long as it is a Shape of some kind.

the beauty here is that later, if somebody makes a Hexagon, Trapazoid or a Parallelagram class that extends your Shape class, you don't have to change your code around the array.
 
Brandt Charles
Ranch Hand
Posts: 57
Chrome IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you both for your input. Fred, your explanation made it even more clear.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!