Difference between “this” and“super” keywords in Java

前端 未结 9 1861
你的背包
你的背包 2020-11-27 03:00

What is the difference between the keywords this and super?

Both are used to access constructors of class right? Can any of you explain?

9条回答
  •  面向向阳花
    2020-11-27 03:24

    From your question, I take it that you are really asking about the use of this and super in constructor chaining; e.g.

    public class A extends B {
        public A(...) {
            this(...);
            ...
        }
    }
    

    versus

    public class A extends B {
        public A(...) {
            super(...);
            ...
        }
    }
    

    The difference is simple:

    • The this form chains to a constructor in the current class; i.e. in the A class.

    • The super form chains to a constructor in the immediate superclass; i.e. in the B class.

提交回复
热议问题