Sunday 23 October 2016

Abstract class Implementation in Java with best Example

Abstract class

If a class contain any abstract method then the class is declared as abstract class. An abstract class is never instantiated. It is used to provide abstraction. Although it does not provide 100% abstraction because it can also have concrete method.

1.)   Abstract class can have abstract and non-abstractmethods.
2.)  Abstract class can have final, non-final, static and non-static variables.
3.)  Abstract class can have static methods, main method and constructor.

(We can use this Program to this Operator / Super Keyword / Upcasting  )

Example Program :

public class AbstractConstructorTest 
  public static void main(String args[]) 
  { 
    Server server = new Tomcat("Apache Tomcat");     //  Upcasting
    server.start();
  }

abstract class Server
{
  protected final String name; // final variable
  
  protected double version  = 8.6;   // non-final variable 
  
  public Server(String name)   //  constructor inside a abstract  class
  { 
    this.name = name; 
  } 
  
  public String normalmethod()
  {
    
return  " started successfully";
    
  }
  
  public abstract boolean start();    //   abstract method
  
}

class Tomcat extends Server
  public Tomcat(String name)
  { 
  super(name); 
}
@Override 
public boolean start() 
  System.out.println( this.name +" - "+ version+ " " +normalmethod() ); 
  return true; 
}
}

Output:

Apache Tomcat - 8.6  started successfully


No comments:

Post a Comment