• Sun. Oct 27th, 2024

Inheritance in Java, Part 2: Object and its methods

Byadmin

Jun 4, 2024


Java’s standard class library consists of thousands of classes and other reference types. Despite the differences in their capabilities, each of these types directly or indirectly extends the Object class. Together, they form one massive inheritance hierarchy.The first half of this tutorial introduced the basics of inheritance in Java. You learned how to use Java’s extends and super keywords to derive a child class from a parent class, invoke parent class constructors and methods, override methods, and more. Now, we’ll turn our focus to the mothership of the Java class inheritance hierarchy, java.lang.Object.Studying Object and its methods will give you a more functional understanding of Java inheritance and how it works in your programs. What you’ll learn in this Java tutorial
All about Object: Java’s superclass
How to extend Object: An example
What Java’s getClass() method does
What Java’s clone() method does
What Java’s equals() method does
What Java’s finalize() method does
What Java’s hashCode() method does
What Java’s toString() method does
What Java’s wait() and notify() methods do
download

Download the source code for example applications in this tutorial. Created by Jeff Friesen.
All about Object: Java’s superclassObject is the root class, or ultimate superclass, of all other Java classes. Stored in the java.lang package, Object declares the following methods, which all other classes inherit:
protected Object clone()
boolean equals(Object obj)
protected void finalize()
Class> getClass()
int hashCode()
void notify()
void notifyAll()
String toString()
void wait()
void wait(long timeout)
void wait(long timeout, int nanos)
A Java class inherits these methods and can override any method that’s not declared final. For example, the non-final toString() method can be overridden, whereas the final wait() methods cannot.We’ll look at each of these methods and how you can use them to perform special tasks in the context of your Java classes. First, let’s consider the basic rules and mechanisms for Object inheritance. How to extend Object: An exampleA class can explicitly extend Object, as demonstrated in Listing 1.Listing 1. Explicitly extending Objectpublic class Employee extends Object
{
private String name;

public Employee(String name)
{
this.name = name;
}

public String getName()
{
return name;
}

public static void main(String[] args)
{
Employee emp = new Employee(“John Doe”);
System.out.println(emp.getName());
}
}Because you can extend at most one other class (recall from Part 1 that Java doesn’t support class-based multiple inheritance), you’re not forced to explicitly extend Object; otherwise, you couldn’t extend any other class. Therefore, you would extend Object implicitly, as demonstrated in Listing 2. Listing 2. Implicitly extending Objectpublic class Employee
{
private String name;

public Employee(String name)
{
this.name = name;
}

public String getName()
{
return name;
}

public static void main(String[] args)
{
Employee emp = new Employee(“John Doe”);
System.out.println(emp.getName());
}
}Compile Listing 1 or Listing 2 as follows:javac Employee.javaRun the resulting application:java EmployeeYou should observe the following output:John DoeWhat Java’s getClass() doesThe getClass() method returns the runtime class of any object on which it is called. The runtime class is represented by a Class object, which is found in the java.lang package. Class is also the entry point to the Java Reflection API, which a Java application uses to learn about its own structure. What Java’s clone() method doesThe clone() method creates and returns a copy of the object on which it’s called. Because clone()’s return type is Object, the object reference that clone() returns must be cast to the object’s actual type before assigning that reference to a variable of the object’s type. The code in Listing 3 demonstrates cloning.Listing 3. Cloning an objectclass CloneDemo implements Cloneable
{
int x;

public static void main(String[] args) throws CloneNotSupportedException
{
CloneDemo cd = new CloneDemo();
cd.x = 5;
System.out.println(“cd.x = ” + cd.x);
CloneDemo cd2 = (CloneDemo) cd.clone();
System.out.println(“cd2.x = ” + cd2.x);
}
}Listing 3’s CloneDemo class implements the Cloneable interface, which is found in the java.lang package. Cloneable is implemented by the class (via the implements keyword) to prevent Object’s clone() method from throwing an instance of the CloneNotSupportedException class (also found in java.lang).CloneDemo declares a single int-based instance field named x and a main() method that exercises this class. main() is declared with a throws clause that passes CloneNotSupportedException up the method-call stack.main() first instantiates CloneDemo and initializes the resulting instance’s copy of x to 5. It then outputs the instance’s x value and calls clone() on this instance, casting the returned object to CloneDemo before storing its reference. Finally, it outputs the clone’s x field value. Compile Listing 3 (javac CloneDemo.java) and run the application (java CloneDemo). You should observe the following output:cd.x = 5
cd2.x = 5Overriding clone()We didn’t need to override clone() in the previous example because the code that calls clone() is located in the class being cloned (CloneDemo). If the call to clone() were located in a different class, then you would need to override clone().Because clone() is declared protected, you would receive a “clone has protected access in Object” message if you didn’t override it before compiling the class. Listing 4 is a refactored version of Listing 3 that demonstrates overriding clone().Listing 4. Cloning an object from another classclass Data implements Cloneable
{
int x;

@Override
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}

class CloneDemo
{
public static void main(String[] args) throws CloneNotSupportedException
{
Data data = new Data();
data.x = 5;
System.out.println(“data.x = ” + data.x);
Data data2 = (Data) data.clone();
System.out.println(“data2.x = ” + data2.x);
}
}Listing 4 declares a Data class whose instances are to be cloned. Data implements the Cloneable interface to prevent a CloneNotSupportedException from being thrown when the clone() method is called. It then declares int-based instance field x, and overrides the clone() method. The clone() method executes super.clone() to call its superclass’s (that is, Object’s) clone() method. The overriding clone() method identifies CloneNotSupportedException in its throws clause.Listing 4 also declares a CloneDemo class that: instantiates Data, initializes its instance field, outputs the value of the instance field, clones the Data object, and outputs its instance field value.Compile Listing 4 (javac CloneDemo.java) and run the application (java CloneDemo). You should observe the following output:data.x = 5
data2.x = 5Shallow cloningShallow cloning (also known as shallow copying) refers to duplicating an object’s fields without duplicating any objects that are referenced from that object’s reference fields (if there are any reference fields). Listings 3 and 4 actually demonstrated shallow cloning. Each of the cd-, cd2-, data-, and data2-referenced fields identifies an object that has its own copy of the int-based x field.Shallow cloning works well when all fields are of the primitive type and (in many cases) when any reference fields refer to immutable (unchangeable) objects. However, if any referenced objects are mutable, changes made to any one of these objects can be seen by the original object and its clone(s). Listing 5 demonstrates.



Source link