• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can I instantiate a interface?

 
thomas davis
Ranch Hand
Posts: 207
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can I instantiate a interface?
ServletContext is a interface and we are using following snippet..
ServletContext context = getServletContext();

Could somebody explain the basics of above written snippet?

Connection con = DriverManager.getConnection();
Connection is an inteface,how we do make object out of it?
 
Devesh H Rao
Ranch Hand
Posts: 687
Hibernate jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ServletContext context = getServletContext();
The context is just a handle to hold a object returned by the method getServletContext() which in turn has implemented ServletContext interface

for example let me say
// a interface similar to ServletContext
public interface IAnimal{
public String getName();
}
// a class imlementing the declared interface
public class Human implements IAnimal{
public void getName(){return "Human"};
}
// a class imlementing the declared interface
public class Ape implements IAnimal{
public void getName(){return "Ape"};
}
public class Test{
public Test(){

}
public IAnimal getAnimal(){

//here i can return either a Human/Ape object
}
psvm(Strings args[]){
Test t = new Test();
// code similar to ServletContext context = getServletContext();
IAnimal _iAnimal = t.getAnimal();
}
}
if u want to trace the flow of getServletContext() method
getServletContext() is a metod declared in ServletConfig which itself is a interface which is implemented by GenericServlet further extended by HttpServlet which will return a object (this class may be server specific) implementing ServletContext.
similar is the case with Connection......
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!