Features of the Object Class


Determining the Class That an Object Belongs To

Professor pr = new Professor(); 
System.out.println(pr.getClass().getName());
if(x != null && x.getClass().getName().equals("Professor")) {}
try {
} catch (Exception e) {
    System.out.println("Drat! An exception of type " + e.getClass().getName() + " has occurred.");
}
if(x instanceof Professor) {
    System.out.println("x is a Professor");
}

Testing the equality of objects

What does it mean when we say that two objects are “equal”? When speaking of generic Objects, we say that two objects (or, more precisely, two object references) are equal if they both refer to precisely the same object in memory (i.e., if the references both point to the same exact memory location in the JVM). Java provides two ways for determining the equality of two Object references x and y:

  • The double equal operator (==)
  • The boolean equals method

The String class overrides the equals method as defined by the Object class so that it compares String values rather than String identities. In fact, many of the predefined Java classes have overridden the equals method as inherited from Object to perform a relevant, class-specific comparison—for example, the wrapper classes (Boolean, Integer, Double, etc.), the Date class, and others. And, of course, we can override the equals method for our own classes, as well—let’s see how this is accomplished.

Overriding the Equals method

public class Person { 
    private String ssn; 
    private String name; 

    // Constructor. 
    public Person(String s, String n) { 
        this.setSsn(s); 
        this.setName(n); 
    }

    // Overriding the equals method that we inherited from the Object class. 
    public boolean equals(Object o) { 
        boolean isEqual; 
        // Try to cast the Object reference into a Person reference. 
        // If this fails, we'll get a ClassCastException. 

        try { 
            Person p = (Person) o; 
            // If we make it to this point in the code, we know we're 
            // dealing with a Person object; next, we'll compare ssn's. 

            if (this.getSsn().equals(p.getSsn())) { 
                // We'll deem p equal to THIS person. 
                isEqual = true; 
            } else { 
                isEqual = false; 
            } 
        } catch (ClassCastException e) { 
            // They're not equal - o isn't even a Person! 
            isEqual = false; 
        } 
    return isEqual; 
    } 

}

Overriding the toString method

Studen s = new Stunden();
System.out.println(s.toString());

Student@71f71130 represents an internal object ID relevant only to the JVM. It just so happens that all objects inherit a method from the Object class with the header String toString();

public String toString() { 
    return this.getName() + " (" + this.getSsn() + ")"); 
}

results matching ""

    No results matching ""