Sunday, January 11, 2009

Abstract Classes and Abstract Methods (Java Fundamentals)

You have to know two important concepts for this part. One is Abstract classes and the other is Interface. Depends on the nature of the project, you need to set certain level of standards and rules that the other developers must follow. This is where Abstract classes and Interfaces come into picture. Abstract classes are usually used on small and big time projects, where it can have code implementation like general classes and also declare Abstract methods (empty methods that require implementation from the sub-classes). Abstract methods usually serves as a prototype to developers.

Lets take an example of a Car, every car has seats but the number of seats vary based on the type of car. A sports car will have 2 seats and an economic family car has 4 seats. At this point the common feature for every car are seats, so we need to create an Abstract class called Car and an abstract method called seat. Than we can create 2 sub-classes called SportsCar and EconomicCar that will override the seat method of Car class.


public abstract Car{
public abstract int seat() ;
}

public class SportsCar extends Car{
public int seat()
{
int seat = 2 ;
return seat ;
}
}

public class EconomicCar extends Car{
public int seat()
{
int seat = 4 ;
return seat ;
}
}


Here are the rules of an Abstract class and method:

  1. Abstract classes cannot be instantiated
  2. Abstract class can extend an abstract class or a concrete class and implement several interface classes
  3. Abstract class cannot extend an interface
  4. If a class contains Abstract method, the class has to be declared Abstract class
  5. An Abstract class may or may not contain an Abstract method
  6. Abstract method should not have any code implementations, the sub-classes must override it (sub-class must give the code implementations).
  7. If a sub-class of an Abstract class does not override the Abstract methods of its super-class, than the sub-class should be declared Abstract also.
  8. Abstract method cannot be declared with any other non-access modifiers such as static, final, native, transient, volatile
  9. Abstract classes can only be declared with public and default access modifiers.
  10. Abstract methods can only be declared with public, default and protected modifier.



Author: Thiagu

No comments:

Post a Comment