• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt related to Interface...

 
Raveendra Mutyala
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Connection conn= DriverManager.getConnection("jdbc dbc:sqlserver");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("Select * from sysobjects");


in this, we know that Connection and Statements are Interface's , so how can the objects be created and referred by 'conn' and 'st' objects in the above example even though they are interfaces..
We know that for an interface only subclass objects can be referenced so what about the above case?...

the st.executeQuery() is just signature in the interface so,where is that methods functionality implemented...

Can some one help me in clarifing the doubt ..
i Will be very thankful to u if u help me about it...

Truly Friend ,
Awaiting for ur valuable replies..
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically the reference is of an interface type, which is legal. The actual instance of the object is what the "factory" methods are creating. you don't need to know the specific type of instance, you can use an interface to reference any instance that implements that interface.

That way you code to use any type of Connection class will always be the same and never need to change based on the actual Connection object instance type.

This is called coding to an interface, which is a very powerful too in OO and makes many great Design Patterns possible.

Hope that helps.

Mark
 
Ryan McGuire
Ranch Hand
Posts: 1068
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this:


You'll see that the concrete class of, say, conn isn't Connection, but rather something like SqlServerODBCConnection. That class "implements" the Connection interface. In that sense, conn "is a" Connection and can be used anywhere a Connection is called for.

Mark wrote...

That way you code to use any type of Connection class will always be the same and never need to change based on the actual Connection object instance type.


In a word, Polymorphism. That's one of the cornerstones of OO.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic