..
The Object Class
There is one special class, Object, defined by Java. All other classes are subclasses of Object. That is, Object is a superclass of all other classes. This means that a reference variable of type Object can refer to an object of any other class. Also, since arrays are implemented as classes, a variable of type Object can also refer to any array.
Object defines the following methods, which means that they are available in every object.
The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may override the others. These methods are described elsewhere in this book. However, notice two methods now: equals( ) and toString( ). The equals( ) method compares two objects. It returns true if the objects are equal, and false otherwise. The precise definition of equality can vary, depending on the type of objects being compared. The toString( ) method returns a string that contains a description of the object on which it is called. Also, this method is automatically called when an object is output using println( ). Many classes override this method. Doing so allows them to tailor a description specifically for the types of objects that they create.
Object Class Methods
- protected Object clone()
- boolean equals(Object obj)
- protected void finalize()
- Class<?> getClass()
- int hashCode()
- void notify()
- void notifyAll()
- void wait()
- String toString()
- public final void notify()
- public final void notifyAll()
- public final void wait()
- public final void wait(long timeout)
- public final void wait(long timeout, int nanos)
1. protected Object clone() Method
x.clone() != x
x.clone().getClass() == x.getClass()
x.clone().equals(x)
protected Object clone() Method Example
public class ObjectClass {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date.toString());
Date date2 = (Date) date.clone();
System.out.println(date2.toString());
}
}
Tue Sep 04 14:15:00 IST 2018
Tue Sep 04 14:15:00 IST 2018
public class Person implements Cloneable {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public Object clone() throws CloneNotSupportedException {
Person person = (Person) super.clone();
return person;
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
}
public static void main(String[] args) throws CloneNotSupportedException {
Person person = new Person();
person.setFirstName("Ramesh");
person.setLastName("Fadatare");
System.out.println(person.toString());
Person person2 = (Person) person.clone();
System.out.println(person2.toString());
}
}
Person [firstName=Ramesh, lastName=Fadatare]
Person [firstName=Ramesh, lastName=Fadatare]
@Override
public Object clone() throws CloneNotSupportedException {
Person person = (Person) super.clone();
return person;
}
2. boolean equals(Object obj)
- It is reflexive: for any non-null reference value x, x.equals(x) should return true.
- It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
- It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
- It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
- For any non-null reference value x, x.equals(null) should return false.
boolean equals(Object obj) Example
// get an integer, which is an object
Integer x = new Integer(50);
// get a float, which is an object as well
Float y = new Float(50f);
// check if these are equal,which is
// false since they are different class
System.out.println("" + x.equals(y));
// check if x is equal with another int 50
System.out.println("" + x.equals(50));
false
true
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
public class Person implements Cloneable { private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
}
public static void main(String[] args) throws CloneNotSupportedException {
Person person = new Person();
person.setFirstName("Ramesh");
person.setLastName("Fadatare");
Person person1 = new Person();
person1.setFirstName("Ramesh");
person1.setLastName("Fadatare");
boolean hasEqual = person.equals(person1);
System.out.println("Both objects equal :: " + hasEqual);
}
}
Both objects equal :: true
3. protected void finalize() Method
protected void finalize() Method Example
public class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
// This method is called just before an object is garbage collected
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
super.finalize();
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
}
public static void main(String[] args) {
Person person = new Person();
person.setFirstName("Ramesh");
person.setLastName("Fadatare");
System.out.println("Before Finalize");
try {
person.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("After Finalize");
}
}
Before Finalize
After Finalize
4. Class<?> getClass() Method
Class<?> getClass() Method Example
public class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.getClass());
}
}
class com.javaguides.corejava.lang.Person
4. int hashCode() Method
- Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
- If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
- It is not required that if two objects are unequal according to the java.lang.Object.equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
int hashCode() Method Example
public class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
public static void main(String[] args) {
Person person = new Person();
person.setFirstName("Ramesh");
person.setLastName("Fadatare");
System.out.println(person.hashCode());
Person person1 = new Person();
person1.setFirstName("Ramesh");
person1.setLastName("Fadatare");
System.out.println(person1.hashCode());
}
}
-1066062211
-1066062211
6. notify() , 7. notifyAll() and 8. wait() Methods
- void notify() - This method wakes up a single thread that is waiting on this object's monitor.
- void notifyAll() - This method wakes up all threads that are waiting on this object's monitor.
- void wait() - This method causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
notify() , 7. notifyAll() and 8. wait() Methods Example
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class ObjectClassNotifyNotifyAllAndWaitExample {
private List<String> synchedList;
public ObjectClassNotifyNotifyAllAndWaitExample() {
// create a new synchronized list to be used
synchedList = Collections.synchronizedList(new LinkedList<>());
}
// method used to remove an element from the list
public String removeElement() throws InterruptedException {
synchronized (synchedList) {
// while the list is empty, wait
while (synchedList.isEmpty()) {
System.out.println("List is empty...");
synchedList.wait();
System.out.println("Waiting...");
}
String element = synchedList.remove(0);
return element;
}
}
// method to add an element in the list
public void addElement(String element) {
System.out.println("Opening...");
synchronized (synchedList) {
// add an element and notify all that an element exists
synchedList.add(element);
System.out.println("New Element added:'" + element + "'");
synchedList.notifyAll();
System.out.println("notifyAll called!");
}
System.out.println("Closing in AddElement method...");
}
public static void main(String[] args) {
final ObjectClassNotifyNotifyAllAndWaitExample demo = new ObjectClassNotifyNotifyAllAndWaitExample();
Runnable runA = () -> {
try {
String item = demo.removeElement();
System.out.println("" + item);
} catch (InterruptedException ix) {
System.out.println("Interrupted Exception!");
} catch (Exception x) {
System.out.println("Exception thrown.");
}
};
Runnable runB = () -> {
// run adds an element in the list and starts the loop
demo.addElement("Hello!");
};
try {
Thread threadA1 = new Thread(runA, "A");
threadA1.start();
Thread.sleep(500);
Thread threadA2 = new Thread(runA, "B");
threadA2.start();
Thread.sleep(500);
Thread threadB = new Thread(runB, "C");
threadB.start();
Thread.sleep(1000);
threadA1.interrupt();
threadA2.interrupt();
} catch (InterruptedException x) {
}
}
}
List is empty...
List is empty...
Opening...
New Element added:'Hello!'
notifyAll called!
Waiting...
Closing in AddElement method...
Hello!
Waiting...
List is empty...
Interrupted Exception!
9. String toString() Method
String toString() Method Example
public class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
}
public static void main(String[] args) {
Person person = new Person();
person.setFirstName("Ramesh");
person.setLastName("Fadatare");
System.out.println(person.toString());
}
}
Person [firstName=Ramesh, lastName=Fadatare]
..
https://www.javaguides.net/2018/09/object-class-methods-in-java-with-examples.html
https://www.brainkart.com/article/The-Object-Class---Java_10450/
https://moonlightenoch.wordpress.com/2012/02/24/java-se-review-generics-and-collections/
No comments:
Post a Comment