Saturday, June 1, 2013

Abstracttion with Abstract class

Abstraction is the ability to provide a class abstract in OOP. Abstract class can not be instantiated. All other property of Abstract class is same as normal class. but we can not instantiate abstract class.

We have to use abstract keyword to declare abstract class.



/* File name : Company.java */
public abstract class Company
{
   private String a;
   private String b;
   private int c;
   public Company(String a, String b, int c)
   {
      System.out.println("constructor");
      this.a= a;
      this.b= b;
      this.c= c;
   }
   public double a()
   {
     System.out.println("a");
     return 0.0;
   }
   public void b()
   {
      System.out.println("b");
   }
   public String toString()
   {
      return a+ " " + b+ " " + c;
   }

   public String b()
   {
      return b;
   }

}


Above class have same declaration and implementation just like simple class. but is have declared as abstract class. But the question is What is the difference between Abstract class and normal class.
I have provide below example to understand abstract class.


if you would try as follows:

/* File name : AbstractDemo.java */
public class AbstractDemo
{
   public static void main(String [] args)
   {
 
      Company e = new Company("Abhi", "India", 22);

      System.out.println("\n its my name--");
      e.b();
    }
}


 When we compile above class then you would get following error:

Company .java:46: Employee is abstract; cannot be instantiated

      Company e = new Company ("abhi.", "india", 22);
                   ^
1 error

We can not instantiate Abstract Class. rather you can create instance of  anonymous subclass of your abstract class. below example describes how can i do it.


public class AbstractDemo
{
   public static void main(String [] args)
   {
   
      Company e = new Company("Abhi", "India"){

      @Override
        public void mailCheck() {  // You need to implement abstract method
            System.out.print("Abstract");
        }

                               };

      e.b();
    }
}


From above example we can instantiate abstract class anonymous subclass.

No comments:

Post a Comment