Tuesday, 31 July 2012

Abstract classes and Interfaces

Abstract class
Abstract classes are used to define only part of an implementation. As these are partly implemented, information is not complete and thus we cannot instantiate abstract classes.
However these can contain instance variables and methods that are fully implemented. The class that inherits from abstract class is responsible to provide details.

Also any class with an abstract method i.e.method without any implementation must be declared abstract. 

If subclass overrides all abstract methods of the super class, than it becomes a concrete class i.e. we can create its objects. Otherwise we have to declare it as abstract or we cannot compile it. 
Consider the below abstract class:
This Shape class contains an abstract method calculateArea() with no definition. Hence we cannot create objects of this class.
     public abstract class Shape {
       public abstract void calculateArea();

Now to use this abstract class, we create another class - Circle, this extends from abstract Shape class, therefore to become concrete class it must provides the definition of calculateArea() method.
     public class Circle extends Shape {
     private int x, y;
     private int radius;
     public Circle() {
       x = 5;
       y = 5;
       radius = 10;
     // providing definition of abstract method
     public void calculateArea () {
       double area = 3.14 * (radius * radius);
       System.out.println(―Area: ‖ + area);

Interfaces are special java type which contains only a set of method prototypes, but does not provide the implementation for these prototypes. All the methods inside an interface are abstract by default thus an abstract class – a class with zero implementation. 
To define an interface, keyword 'interface' is used instead of 'class'

      public interface InterfaceEx {
         public void printRec();

Contrary to inheritance, a class can implement more than one interface. To do this separate the interface names with comma. This is java’s way of multiple inheritance.

Using interface:
Classes implements interfaces. A class that implements an interface will have to provide definition of all the methods that are present inside an interface. If the class does not provide the definitions of all methods, the class would not compile.

      public class ImplEx implements  InterfaceEx {
        private String name;
        public String toString() {
           return "name:"+name;
        //providing definition of interface’s  printRec method
        public void  printRec () {
           System.out.println("Name:" +name);

No comments:

Post a Comment