Saturday, December 24, 2011

Abstract Class in JAVA (final,exends)

Definition
An abstract class is a class that is declared by using the abstract keyword. It may or may not have abstract methods. Abstract classes cannot be instantiated, but they can be extended into sub-classes.

Points of abstract class :
  1. Abstract class contains abstract methods.
  2. Program can't instantiate an abstract class.
  3. Abstract classes contain mixture of non-abstract and abstract methods.
  4. If any class contains abstract methods then it must implements all the abstract methods of the abstract class.
Example



import java.io.*;
import java.lang.*;
abstract class Ashape
{
      public final double pi=3.14;
      abstract public double area();
      static int cnt;
      public Ashape()  // contructor
      {
           cnt ++ ;
      }
      public void dispCount()
      {
         System.out.println(cnt);
      }
}
Class Acircle extends Ashape
{
     double r;
     public void setRadius(double r)
     {
         this.r = r;
     }
     public double area()
     {
            return pi * r * r;
     }


}
public class AbstractDemo
{
          public static void main(String args[])
          {
                Ashape s=new Acircle();
                ((Acircle)s).setRadius(10);
                System.out.println(s.area());
                s.dispCount();
          }
}




Final : 
final variable can only be initialized once, either via an initializer or an assignment statement. It need not be initialized at the point of declaration: this is called a 'blank final' variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared: otherwise, a compile-time error occurs in both cases.


Extends:
Extends keyword is used to implement or share the method/variable of parent class within child class.

The Parent class
public class Parent {
     }
The Child class
public class Child extends Parent {
     }

Blank Final  :
The blank final, which was introduced in Java 1.1, is a final variable whose declaration lacks an initializer. A blank final can only be assigned once and must be unassigned when an assignment occurs. In order to do this, a Java compiler runs a flow analysis to ensure that, for every assignment to a blank final variable, the variable is definitely unassigned before the assignment; otherwise a compile-time error occurs.
In general, a Java compiler will ensure that the blank final is not used until it is assigned a value and that once assigned a value, the now final variable cannot be reassigned another value.

1 comment:

  1. Indeed nice post. final is a tricky keyword if used carefully it can boost performance of Java application. I have also shared my view as final keyword in Java let me know how do you find it.

    ReplyDelete