01abstractClass.pdf - Abstract classes and methods We give a simple explanation of abstract classes and abstract methods Making a class abstract

01abstractClass.pdf - Abstract classes and methods We give...

This preview shows page 1 out of 1 page.

Abstract classes and methods We give a simple explanation of abstract classes and abstract methods. Making a class abstract Consider class Shape and one of its subclasses, Circle, outlined to the right. There would be other subclasses, like Rectangle, and Triangle. Class Shape is there to hold information that is common to all subclasses, like the position of a shape in a GUI window. We don’t want users to create instances of class Shape because an instance really isn’t a shape; all it holds is the position of shapes. In order to prevent users from creating instances of class Shape, make Shape abstract by putting keyword abstract between public and class : public abstract class Shape { … } Doing that makes the expression new Shape(…) illegal; if you use it, your program won’t compile. You can still have Shape variables. Example: you can do this: Shape sp= new Circle(5, 10, 2.5); But you can’t do this: Shape sp= new Shape(5, 10); Reason for making a class abstract: So you cannot create in- stances of it; it cannot be “newed”.
Image of page 1

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture