Trouble trying to grasp inheritance

前端 未结 3 1370
南方客
南方客 2021-01-07 03:45

Given Main.java:

public class Main{
    public static void main(String[]args){
          A a = new B();
          a.print();
    }

}

class A{
       A() {p         


        
3条回答
  •  鱼传尺愫
    2021-01-07 04:30

    B doesn't have any constructor, so its default constructor won't do anything except calling A's constructor.

    Now when B's default constructor is called, it calls A's constructor (keep in mind i is still not set, so default value 0). A's constructor calls print(), now as object is of actually B it calls B's print() and it prints 0 (remember i was not set).

    Now once these constructor calls completes B's code gets executes which sets i to 0. Now calling print() will again get you to B's print() (as object is of B only) which will print 4.

    "DEBUGGING IS THE KEY"

提交回复
热议问题