Abstract class what is
By: Satish Balakrishnan. Dictionary Dictionary Term of the Day. Natural Language Processing. Techopedia Terms. Connect with us. Sign up. Term of the Day. Best of Techopedia weekly. News and Special Offers occasional. Others require different implementations for example, resize or draw. All GraphicObject s must be able to draw or resize themselves; they just differ in how they do it.
This is a perfect situation for an abstract superclass. You can take advantage of the similarities and declare all the graphic objects to inherit from the same abstract parent object for example, GraphicObject as shown in the following figure.
First, you declare an abstract class, GraphicObject , to provide member variables and methods that are wholly shared by all subclasses, such as the current position and the moveTo method. GraphicObject also declares abstract methods for methods, such as draw or resize , that need to be implemented by all subclasses but must be implemented in different ways.
The GraphicObject class can look something like this:. Each nonabstract subclass of GraphicObject , such as Circle and Rectangle , must provide implementations for the draw and resize methods:. In the section on Interfaces , it was noted that a class that implements an interface must implement all of the interface's methods.
Suppose we were modeling the behavior of animals, by creating a class hierachy that started with a base class called Animal. Animals are capable of doing different things like flying, digging and walking, but there are some common operations as well like eating and sleeping. Some common operations are performed by all animals, but in a different way as well.
When an operation is performed in a different way, it is a good candidate for an abstract method forcing subclasses to provide a custom implementation. An abstract method is a method that is declared without an implementation without braces and followed by a semicolon , like this: abstract void sum int a, int b ; Consider using abstract classes if any of these statements apply to your situation: You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields or require access modifiers other than public such as protected and private. You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes. You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
You want to take advantage of multiple inheritances.
0コメント