Saturday, February 7, 2009

abstract class

We can apply abstract keyword for the classes and methods .abstract keyword is not possible for variables.If method declared as abstract we don’t know implementation child class is responsible to provide the implementation for the parent class abstract methods.

Abstract public void m1(); // here ; is mandatory.

Abstract method has declaration only and should not have any implementation.
This is the way of decorating abstract method .we should not keep curly braces at end.

  • If a class contain at least one abstract method we should have to declare that class as abstract other wise compile time error.
  • An abstract class is not compulsory to have an abstract method.i.e abstract class may contain zero number of abstract methods also.this is for restricting object creation.
  • HttpServlet class doesn’t contain any abstract methods ,still the class is declared as abstract because the methods present in HttpServlet can’t provide any request ,response for the end user ,these methods are just for sending error information.
  • It’s a good programming practice to use abstract methods ,abstract classes and interfaces.
Example:
class Sam
{
abstract void m1(); //error
}

Example 2:
abstract class Xy
{
abstract void m1(); // valid
}

Example 3:
abstract class X
{
void m1() // valid
{
System.out.println(“valid”);
}
}

Example 4:
abstract class X
{
abstract void m2();
}

class Y extends X // error we must provide the implementation for m2 method .
{
}

Abstract class examples

0 comments:

Post a Comment