Which should inherit what?

This is one of OOP’s boring academic questions, but it’s not homework. I got a question from a novice programmer about one of these silly examples of OOP tutorials.

Imagine that you are designing a square class and a Cube class that should inherit which?

I see a relationship, but what it is, I really don’t see!

Could you give me a logical argument in the mind of OOP.

+3
source share
8 answers

None! Since a square is not a cube, and a cube is not a square, none of them should inherit from the other. A square can inherit from a polygon, and a cube can inherit from a polyhedron, but both of them are mutually exclusive.

+22

. - "is-a" (, "is-a" , ). , - .

, , . - , 6 ( , 6 , ), , . "is-a" , ...

, , , . Square extends Rectangle. :

, . changeArea (double area) getSide(), Cube. , 6 ( 6 ).

, Square Cube: setVolume ( ), ,

, , GeometryObjectWithEqualSides, .:)

+14

.

+6

+1
struct Square // Rectangle actually
{
  Square( int dx, int dy ) : dx(dx), dy(dy) {};

  int dx;
  int dy;

  int floor_area() { return dx*dy; };
};

struct Cube : Square  // Cuboid actually
{
  Cube( int dx, int dy, int dz ) : Square(dx, dy), dz(dz) {};

  int dz;

  int cube_area() { return floor_area()*2+dx*dz*2+dy*dz*2; };
};

, .

+1

"Hypercube", (0 ), (1 ) , . Hypercube ( , , n- ).

/, , , .. .

. Hypercube .

+1

. , - . , .

, , ;)

0

, . . , : . , Square ? ? , : Square Cube? , : " , ", " , ", - , , . , , , .

, " 6 " - , .

0
source

Source: https://habr.com/ru/post/1712894/


All Articles