简体   繁体   中英

Defining all abstract method in one concrete class

I have major issues in understanding the major topic of OOP. Though I been through Dietel book. I have an abstract class shape.

public abstract class Shape
{
public abstract area();
public absract volume;
}
public class Circle extends Shape
{
//definition of area method
}
public class Sphere extends Shape
{
//define volume method
// define area method
}

Now as I have Shape class as Parent class and Circle class as child class, at same time Shape class is an abstract class, Now I want to define area method in Circle class but not volume method, I want to define volume method in Sphere class. But when i do this, it shows me error but if i define both method in Circle class then it works fine. But then Circle class have extra code of volume which is not use of Circle class.

An abstract member is not an optional member. It is a member that MUST be implemented for implementing a concrete class. If one of the abstract member is not defined in a derived class, this class is also abstract and cannot be instantiated.

This is an excellent example for the Interface Segregation Principle : your interface for Shape combines the interfaces of different potentially unrelated concepts: area() which is only relevant for 2D shapes, and volume() is only relevant for 3D shapes.

If you want a clean SOLID design, you'd need to consider a Shape2D with area() and perimeter() and a Shape3D with a surface() and volume() .

If you think that the area() is in fact the same thing than a surface() , you may consider an abstract parent Shape that provides an abstract surface() , a child Shape2D that provides for the perimeter() and another child Shape3D that provides the volume() .

More pragmatically, you could consider that the volume() of of a Circle or any other 2D shape is simply 0 and stick to your original design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM