Previous | Home | Next |
The abstract modifier may be applied to a class or a method, but not to a variable. A class which is declared abstract cannot be instantiated .i.e. its object cannot be created because it is not fully implemented.
There is a relationship between an abstract class and an abstract method which is, if a class has one or more abstract methods, it must be declared abstract. A class may define abstract methods in any of the following ways:
-
A class may have one or more abstract methods defined in it.
-
A class might have inherited one or more abstract methods from its superclass, and has not provided implementation for all or some of them.
-
A class declares that it implements an interface, but does not provide implementation for at least one method in the interface.
In above shown cases, the class must be declared abstract.But, if there is no abstract method in the class, it could still be declared abstract but in this case the class cannot be instantiated. Following code snippet will give a good idea about the abstract modifier,
Example
abstract class Shape // declaring an abstract class { abstract void Area(); // an abstract method with no body void Printanything() // a simple method { System.out.println("hello!! Shashi Chaudhary @ r4r"); } } Java Tutorialslass Rectangle extends Shape // defined a class which is inheriting Shape class { int length; int breadth; Rectangle(int length, int breadth) { this.length=length; this.breadth=breadth; } void Area() // implementing the Area() method defined in Shape class { System.out.println("The area of rectangle is given by :"+(length*breadth)); // displaying area of rectangle } } Java Tutorialslass Java Tutorialsircle extends Shape { int radius; Java Tutorialsircle(int radius) {[an error occurred while processing this directive] this.radius=radius; } void Area() // Implementing the Area() method defined in class Shape { System.out.println("The area of circle is given by :"+(Math.PI*radius*radius)); // displaying area of circle } } Java Tutorialslass AbstractModifierExample { public static void main(String args[]) { // Shape shp = new Shape(); /* will cause compilation error as Shape is defined abstract Rectangle objrect = new Rectangle(7,5); Java Tutorialsircle objcirc = new Java Tutorialsircle(7); objrect.Area(); objcirc.Area(); objcirc.Printanything(); // accessing the method defined in class Shape through Circle's instance objrect.Printanything(); // accessing the method defined in class Shape through Rectangle's instance } }
A abstract class is some what opposite to the final class. A final class cannot be extended or inherited, whereas an abstract class must be extended, before it can be instantiated. An abstract class or an abstract method means it’s not fully implemented .i.e if you want to use it, you have to implement it.
Previous | Home | Next |