我有如下代码:
Class A{
protected void method1(){
//i have logic which will fetch the results from the database
}
}
我还有一个扩展类 A 的类:
Class B extends A{
//some logic
}
现在执行了多少数据库调用?一个或两个?
我有如下代码:
Class A{
protected void method1(){
//i have logic which will fetch the results from the database
}
}
我还有一个扩展类 A 的类:
Class B extends A{
//some logic
}
现在执行了多少数据库调用?一个或两个?
如果你这样做:
new B().method1()
method1()代表B对象只调用一次。JVM 正在做的是它首先尝试找到B.method1()。如果它在 中被覆盖,B它将调用它(并完全跳过A.method1())。但是由于B没有覆盖它,A.method1()因此透明地调用了 original 。
如果B会覆盖method1()调用 original 的唯一方法A.method1()是调用super.method1()inside B。
如果您已经在重写方法中编写了逻辑,那么B在任何情况下,当您的调用methodm1不考虑类时,仅one调用都会转到数据库,直到您调用方法两次为止。