Answer to Question #137278 in Java | JSP | JSF for Abiemwense E Okuonghae

Question #137278
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-10-07T14:22:30-0400

Subclass:

public class Manager extends Employee {
	private double bonus;
	private ArrayList<Employee> team;
	public Manager(String firstName, String lastName, ArrayList<Employee> team) {
		// using "super" as constructor
		super(firstName, lastName);
		// using "super" as variable
		super.bonus = 0.2;
		// using "this" as variable
		this.bonus = 0.3;
		this.team = team;
	}
	public Manager(String firstName, String lastName) {
		// using "this" as constructor
		this(firstName, lastName, new ArrayList<Employee>());
	}
	@Override
	public double getSalary() {
		// using "super" as method
		return super.getSalary() * (1 + this.bonus);
	}
}

Superclass:

public class Employee {
	private String firstName;
	private String lastName;
	protected double bonus = 0.25;
	private double salary;
	public Employee(String firstName, String lastName) {
		// using "this" as variable.
		this.firstName = firstName;
		this.lastName = lastName;
		this.salary = 4000;
	}
	public double getSalary() {
		return salary * (1 + this.bonus);
	}
	@Override
	public String toString() {
		return "Employee [firstName=" + firstName + ", lastName=" + lastName + ", salary=" + getSalary() + "]";
	}
}

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