gpt4 book ai didi

java - Connection、Statement 等预定义接口(interface)的抽象方法如何在没有主体的情况下执行某些任务?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:00:23 24 4
gpt4 key购买 nike

java中有很多预定义的接口(interface),如ResultSetConnectionStatement等。接口(interface)只能有抽象方法(未实现的方法) .那么为什么我们不先定义它们就使用那里的方法。

例如下面的jdbc代码

public class JDBCSample {

public static void main( String args[]) {

String connectionURL = "jdbc:postgresql://localhost:5432/movies;
user=java;password=samples";`

try {

Class.forName("org.postgresql.Driver");


Connection con = DriverManager.getConnection (connectionURL);


Statement stmt = con.createStatement();


ResultSet rs = stmd.executeQuery("select moviename, releasedate from movies");

while (rs.next())
{....do something.....}
}catch (SQLException e)
{e.printStackTrace();}
catch (Exception e)
{ e.printStackTrace();}}

这里我们调用ConnectionStatement接口(interface)的抽象createStatement()executeQuery()方法?如果是,那么抽象方法(没有主体的方法)如何执行某些任务?

最佳答案

调用:

System.out.println(con.getClass());

并注意实际对象不是Connection 类型。这称为多态性。简单地说,DriverManager.getConnection() 返回实现 Connection东西。您正在调用那个东西 的方法。这是多态性的优势 - JDBC 驱动程序稍后可以决定更改某些内容,只要它实现了Connection,您的代码就不能少关心。

简单的例子:

List<String> list = new ArrayList<String>();
list.size(); //calling abstract method?!? No!

在上面的例子中我们实际上调用了ArrayList.size()

关于java - Connection、Statement 等预定义接口(interface)的抽象方法如何在没有主体的情况下执行某些任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7811265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com