• Post Reply Bookmark Topic Watch Topic
  • New Topic

abstract classes  RSS feed

 
Mohamad Samy
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say I have the following code
The shape is an abstract class that contains two abstract methods, getArea() and getVolume().
I have rectangle class that extends this one but only I want to implement the getArea() method, when I am doing this and keeping the other volume method abstract the compiler give me error that class rectangle must be declared abstract or implement the getVolume method that I don't want.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If Rectangle doesn't implement the getVolume() method, then it must be declared abstract, since it has an abstract method (getVolume(), inherited from Shape) which is not implemented.

If you want Rectangle to be concrete (the opposite of abstract - able to be directly instantiated without any further subclassing), then you need to provide an implementation of the getVolume() method. If you are running into this problem in real life, then chances are your abstract class is to broad. Why do you define getVolume() in the Shape class' contract if not all Shapes have a volume? Perhaps you should have a broader class heirarchy:
Shape: an abstract class which defines the abstract method getArea()
3DShape extends Shape: an abstract class which also defines the abstract method getVolume()
Rectangle extends Shape: a concrete class which implements the getArea() method.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Alternatively, you can make the argument that 2D "objects" has no volume in a 3D space, hence, their volume should be zero.

Henry
 
Mohamad Samy
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have done what steve exactly said; I made a 2d abstract class for the rectangles and 3d abstract class that contain the get volume method. So, now rectangle extends from 2d which has no get volume method. thanks;
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Surely Shape is an abstract class with getArea and getPerimeter methods??? A 2D shape will have a perimeter, even if it has no volume.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!