Question #126866

Give examples showing how "super" and "this" are useful with inheritance in Java. Include examples of using "super" and "this" both as constructors and as variables.

Expert's answer

package com.sadkoala.test;

public class ClassA {

    protected int a;

    public ClassA(int a) {
        this.a = a;
    }

    public void printFields() {
        System.out.println("field a=" + a);
    }
    
}

package com.sadkoala.test;

public class ClassB extends ClassA {

    protected int b;
    protected int c;

    public ClassB(int a, int b, int c) {
        this(a, b);
        this.c = c;
    }

    public ClassB(int a, int b) {
        super(a);
        this.b = b;
    }

    public void printFields() {
        super.printFields();
        System.out.println("Field b=" + b);
        System.out.println("Field c=" + c);
    }

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS