Abstract classes are defined using "abstract" keyword. They contain both abstract methods and concrete methods. Abstract methods do not have any implementation. Any method which has a body is known as a concrete method. An abstract class can have constructors.
An abstract class may or may not include abstract methods. Abstract classes cannot be instantiated but they can be sub-classed i.e., objects cannot be created but sub classes for abstract classes can be created.
Note :
- An abstract class may have complete methods i.e., with full body (concrete methods)
- An normal class may be declared abstract for design purposes.
- A reference variable created to the abstract class can point to the objects of the sub-classes whereby run-time polymorphism is achieved. Ex. : GraphicalObject obj = new Rectangle();
- If there are one or more abstract methods in a class it MUST be labelled as abstract.
Understanding Abstract Classes with Example :
Consider graphical drawings such as lines, curves, rectangles, circles etc., which have certain states such as position, orientation, color etc., and certain behaviors such as rotate, re-size, draw etc.
Save the Following Program as AbstractClassesExample.java : http://pastie.org/6031909
An abstract class may have static fields and static methods. Static members can be used normally using the syntax AbstractClass.staticMethod().
Abstract Methods
In the above example program, display() and area() are declared abstract in the GraphicalObject class. An abstract method doesn't have an implementation i.e., only a parenthesis followed by a semi-colon. All abstract methods SHOULD have a return type. Abstract methods may have parameters.
Example:
abstract void display();
abstract void area();
abstract void moveTo(int a, int b);
Example:
abstract void display();
abstract void area();
abstract void moveTo(int a, int b);
0 comments:
Post a Comment