This section describe about Object Class and it's implementation in java.
Introduction to Object Class
Objects basics
Click here to see objects basics
Object Class
- All the classes defined are subclasses by default.
- Object class is superclass of every class.
- The inheritance happens automatically.
- Your classes will inherit members from the class Object.
Given below some methods and their functions :
| Methods | It's Function |
| toString() | It returns a string which describe the current object. |
| equals() | It is used to compare two objects. |
| getClass() | It returns the current object class. |
| hashCode() | It is used to calculates a hashcode for an object. |
| notify() | wakes up a thread associated with the current object. |
| notifyAll() | wakes up all threads associated with the current object. |
| wait() | causes a thread to wait. |
Example :Getting class name of the object
class Sub {
public Sub(String myname) {
}
}
public class ObjectClass {
public static void main(String args[]) {
Sub s = new Sub("Ankit");
Class classname = s.getClass();
System.out.println(classname.getName());
}
}
Output :
|
C:\Program Files\Java\jdk1.6.0_18\bin>javac ObjectClass.java C:\Program Files\Java\jdk1.6.0_18\bin>java ObjectClass corejava.Sub |
Comparing Objects
In java, objects can be compared using 'equals' method as :
public class EmployeeMain {
public static void main(String[] args) {
Employee emp1 = new Employee("Divya", "Singh");
Employee emp2 = new Employee("Ankit", "Kaushal");
if (emp1.equals(emp2))
System.out.println("These employees are the same.");
else
System.out.println("These are different employees.");
}
}
class Employee {
private String lastName;
private String firstName;
public Employee(String lastName, String firstName) {
this.lastName = lastName;
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public String getFirstName() {
return this.firstName;
}
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (this == null)
return false;
if (this.getClass() != obj.getClass())
return false;
Employee emp = (Employee) obj;
return this.lastName.equals(emp.getLastName())
&& this.firstName.equals(emp.getFirstName());
}
}
Output :
|
C:\Program Files\Java\jdk1.6.0_18\bin>javac EmployeeMain.java C:\Program Files\Java\jdk1.6.0_18\bin>java EmployeeMain These employees are the same. |

[ 0 ] Comments