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 Interface and its advantage


Interface:
–> If your child classes should all implement a certain group of methods/functionalities but each of the child classes is free to provide its own implementation then use interfaces.
For e.g. if you are implementing a class hierarchy for vehicles implement an interface called Vehicle which has properties like Colour MaxSpeed etc. and methods like Drive(). All child classes like Car Scooter AirPlane SolarCar etc. should derive from this base interface but provide a seperate implementation of the methods and properties exposed by Vehicle.
–> If you want your child classes to implement multiple unrelated functionalities in short multiple inheritance use interfaces.
For e.g. if you are implementing a class called SpaceShip that has to have functionalities from a Vehicle as well as that from a UFO then make both Vehicle and UFO as interfaces and then create a class SpaceShip that implements both Vehicle and UFO .

Use an interface

  • When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
  • Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
  • Use an interface to design a polymorphic hierarchy for value types.
  • Use an interface when an immutable contract is really intended.
  • A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.
For Examble:
interface Shape {

 public double area();
 public double volume();
}
public class Point implements Shape {

 static int x, y;
 public Point() {
  x = 0;
  y = 0;
 }
 public double area() {
  return 0;
 }
 public double volume() {
  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