Answer to Question #126866 in Java | JSP | JSF for Mario

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.
1
Expert's answer
2020-07-21T13:35:26-0400
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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS