Class is not abstract and does not override abstract method

前端 未结 2 1708
既然无缘
既然无缘 2020-11-29 06:02

So I\'ve been working on a homework on abstraction for my programming class and fell into a problem. The goal for me right now is to be able to use abstraction, then later b

相关标签:
2条回答
  • 2020-11-29 06:33

    Both classes Rectangle and Ellipse need to override both of the abstract methods.

    To work around this, you have 3 options:

    • Add the two methods
    • Make each class that extends Shape abstract
    • Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:

      abstract class Shape {
          // ...
          void draw(Graphics g);
      }
      

    And

        class Rectangle extends Shape {
            void draw(Graphics g) {
                // ...
            }
        }
    

    Finally

        class Ellipse extends Shape {
            void draw(Graphics g) {
                // ...
            }
        }
    

    And you can switch in between them, like so:

        Shape shape = new Ellipse();
        shape.draw(/* ... */);
    
        shape = new Rectangle();
        shape.draw(/* ... */);
    

    Again, just an example.

    0 讨论(0)
  • 2020-11-29 06:39

    If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.

    In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

    0 讨论(0)
提交回复
热议问题