Print Super Class Fields With Child Instance Fields

Print Super Class Fields With Child Instance Fields

If you want to print all value of child and parent class variables then you will have to override toString() method from object class which prints object values but if you have a class where child parent relationship exists then it will print only child class variable so to include parent class variable as well you will have to tweak method toString(). Please see example below:

  • Parent class: Employer.java:
package com.javahonk;

public class Employer {
	
	private String employerName;
	private String companyLocation;
	
	public Employer(String employerName, String companyLocation) {
		super();
		this.employerName = employerName;
		this.companyLocation = companyLocation;
	}
	public String getEmployerName() {
		return employerName;
	}
	public void setEmployerName(String employerName) {
		this.employerName = employerName;
	}
	public String getCompanyLocation() {
		return companyLocation;
	}
	public void setCompanyLocation(String companyLocation) {
		this.companyLocation = companyLocation;
	}
	@Override
	public String toString() {
		return "Employer [employerName=" + employerName + ", companyLocation="
				+ companyLocation + "]";
	}
	
}
  • Child class: Employee.java (Please have a look toString() method of this class where we are calling super.toString() to print parent class object value:
package com.javahonk;

public class Employee extends Employer{
	
	private  String name;
	private Integer employeeId;
	private Double salary;
	
	public Employee(String employerName, String companyLocation, String name,
			Integer employeeId, Double salary) {
		super(employerName, companyLocation);
		this.name = name;
		this.employeeId = employeeId;
		this.salary = salary;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getEmployeeId() {
		return employeeId;
	}
	public void setEmployeeId(Integer employeeId) {
		this.employeeId = employeeId;
	}
	public Double getSalary() {
		return salary;
	}
	public void setSalary(Double salary) {
		this.salary = salary;
	}
	@Override
	public String toString() {
		return "Employee [name=" + name + ", employeeId=" + employeeId
				+ ", salary=" + salary + "  Parent class: "+super.toString()+"]";
	}

}
  • Test class PrintChidParentObjectData.java to print object value:
package com.javahonk;

public class PrintChidParentObjectData {

	public static void main(String[] args) {
		
		Employee employee = new Employee("Test employee", "USA", "Java Honk", 236985, 1000.00);
		System.out.println(employee);

	}

}
  • Output:

Print Super Class Fields With Child Instance Fields

Leave a Reply

Your email address will not be published. Required fields are marked *