welcome folks
FAQ in android,FAQ in dotnet,DotNet, C#,DOT NET CODE, ASP.NET, VB.NET, TRICKS,Dotnetcode,Android and Latest Technology Articles in VB,Android and ASP.NET

Wednesday, September 5, 2012

Usage Abstract class and its advantage


Abstract Classes
When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.
For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.
The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.

Use an abstract class

  • When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.)
  • Use an abstract class to define a common base class for a family of types.
  • Use an abstract class to provide default behavior.
  • Subclass only a base class in a hierarchy to which the class logically belongs.

For exapmple:
abstract class Shape {

 public String color;
 public Shape() {
 }
 public void setColor(String c) {
  color = c;
 }
 public String getColor() {
  return color;
 }
 abstract public double area();
}
public class Point extends Shape {

 static int x, y;
 public Point() {
  x = 0;
  y = 0;
 }
 public double area() {
  return 0;
 }
 public double perimeter() {
  return 0;
 }
 public static void print() {
  System.out.println("point: " + x + "," + y);
 }
 public static void main(String args[]) {
  Point p = new Point();
  p.print();
 }
}

No comments:

Post a Comment