Java Object Class

In java Object class is present inside java.lang package. Object class is the parent class of all the classes created inside java. In other words, we can say Object class is the topmost class in java class hierarchy.

The Object class provides some common behavior to all the objects such as objects can be compared, the object can be cloned and the object can be notified, etc.

Object class has many predefined methods that can be used using any object in Java.

Object Class Methods-

  • toString()
  • wait()
  • notify()
  • notifyall()
  • getClass()
  • finalize()
  • clone()
  • hashCode()
  • equals()

For Example:

toString method of object class returns string representational form of any object.

package academic;

public class School {

	private String schoolName;
	private String schoolAddress;
	private int schoolStaffCount;

	public School() {
		super();
	}

	/**
	 * @return the schoolName
	 */
	public String getSchoolName() {
		return schoolName;
	}

	/**
	 * @param schoolName the schoolName to set
	 */
	public void setSchoolName(String schoolName) {
		this.schoolName = schoolName;
	}

	/**
	 * @return the schoolAddress
	 */
	public String getSchoolAddress() {
		return schoolAddress;
	}

	/**
	 * @param schoolAddress the schoolAddress to set
	 */
	public void setSchoolAddress(String schoolAddress) {
		this.schoolAddress = schoolAddress;
	}

	/**
	 * @return the schoolStaffCount
	 */
	public int getSchoolStaffCount() {
		return schoolStaffCount;
	}

	/**
	 * @param schoolStaffCount the schoolStaffCount to set
	 */
	public void setSchoolStaffCount(int schoolStaffCount) {
		this.schoolStaffCount = schoolStaffCount;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() { // overriding toString method and giving our own definition
		return "School [schoolName=" + schoolName + ", schoolAddress=" + schoolAddress + ", schoolStaffCount="
				+ schoolStaffCount + "]";
	}
}


package test;

import academic.School;

public class TestSchool {

	public static void main(String[] args) {

		School school = new School();
		school.setSchoolName("Adarsh High School");
		school.setSchoolAddress("Andheri, Mumbai");
		school.setSchoolStaffCount(20);

		System.out.println(school.toString()); //returns String representational of School object

	}
}

Output:
School [schoolName=Adarsh High School, schoolAddress=Andheri, Mumbai, schoolStaffCount=20]

Share