• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 292
  • Last Modified:

instantiate a interface as object

We have interfaces   java.sql.Connection
                &    java.sql.CallableStatement

how to explain

      Connection        _con=Drivermanager.getConnection();
      CallableStatement stmt = _con.prepareCall("...");
      stmt.registerOutParameter(1, Types.INTEGER);
      ResultSet rs=stmt.executeQuery();

stmt is an Object or not,
Does Interface can be instantiated ???

  • 3
  • 2
1 Solution
You are correct in saying that an interface cannot be instantiated. This means that you cannot create that would only be an interface e.g.:

CallableStatement stmt=new CallableStatement();

However, that is not what is happening in the code you provide. An object of type connection is created. This object provides a method called prepareCall that returns an object of TYPE CallableStatement. In this case prepareCall creates an object of some sort, that implements the CallableStatement interface. Such an object CAN be referenced by a "pointer" of type CallableStatement.

This means that you cannot create that
should be
This means that you cannot create an object that

At the end add:
Now that the object has been created, it can be treated as a CallableStatement object.
in simpler terms to what imladris explained nicely ,
the interface has say

interface Guess
public void XXXmethod();

someMethod(Guess g)

now when u say that someMethod expects a param of type Guess ,so if ANY class that implements Guess like so

class AnyClass implements Guess
can be instantiated and passed to someMethod

what happens is that the place where u pass the Guess expects the pointer as imladris said with 1 method having the correct return type and signature as that declared in interface Guess namely
public void XXXmethod()

hope this clears ur doubt
Is there anything else on this topic you would like clarified before you grade the answer?
yesterday the auto-grader graded all 'C' to my locked questions and my points jumped by 4000 or so.
it's better to do the grading by urself and be fair to people who help us out when it's our time to ask questions.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now