0% found this document useful (0 votes)
6 views23 pages

Chapitre 7

The document discusses the Object class in various programming languages, emphasizing its role as a superclass from which all classes inherit. It covers concepts such as cloning objects, equality testing, and the use of the Object class in collections like Vectors in Java and C#. The document also highlights the importance of method overriding for equality checks and the implementation of cloning in Java, including necessary precautions for exception handling.

Uploaded by

issam.salhi.g2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views23 pages

Chapitre 7

The document discusses the Object class in various programming languages, emphasizing its role as a superclass from which all classes inherit. It covers concepts such as cloning objects, equality testing, and the use of the Object class in collections like Vectors in Java and C#. The document also highlights the importance of method overriding for equality checks and the implementation of cloning in Java, including necessary precautions for exception handling.

Uploaded by

issam.salhi.g2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
You are on page 1/ 23

1

Assignments of
Comparison
Cloning,

Objects
07
and
Model Creation Case Study Verification and Validation Conclusion and Perspectives
Introducing the Object Class
Introduction

The summit of the hierarchy, the class of classes, is called in Java the Object class.
Cloning Objects

All classes, whatever they may be, yours as well as those in Java, inherit from the
Object class.

In C#, not only do all classes, but also all structures inherit from the Object class.

Python designers also consider it supreme, though not to the extent of giving it a capital
letter (all these languages clearly distinguish between lowercase and uppercase), and this
superclass has the humble name "object."

It does not exist in C++ or PHP.

2
A Class with a Universal Competence
Introduction

Such a class is typically as an argument or return type of a method that you want to have
universal competence (operable on any kind of object), a method that you can later
Cloning Objects

specialize based on the type of object in question.

This Object class is, therefore, most often a candidate for a "universal" type of usage. Use
it when designing a specific structure type that applies to all objects without distinction of
class, such as a linked list or an expandable array.

3
A Class with a Universal Competence
Introduction

In Java and C#, many collection classes used the Object class. Among the most well-
known examples are the Vector and ArrayList classes, expandable arrays that can contain
Cloning Objects

an undetermined number of objects of any class.

For instance, the methods that were commonly used in Vector include
addElement(Object anObject), which adds an object of any type to the end of the
Vector, and Object elementAt(int i), which returns the object positioned at the "nth
position" of the Vector.

4
A Class with a Universal Competence
Introduction

As you can see, it is indeed the type "Object" that we find in the definition of these
methods. This is normal because nothing in the functionality of this Vector requires
Cloning Objects

knowing the specific type of what it contains.

Since a Vector is generally composed of objects of any class, the use of the method
elementAt(int i) is almost always accompanied by a casting operation to retrieve
the characteristics specific to the extracted object.

5
A Class with a Universal Competence
Introduction

An example of using the Vector class is provided below. We also discover why and how the
ability to type these collections (since the versions of Java 5 and .NET 2) avoids the use
Cloning Objects

of casting. As we will also see, objects have names and can be cloned, but each can do
so in a
import way that is specific to them.
java.util.*;
class O1 {
public void iWorkForO1() {
System.out.println(« Hi, I work for O1");
}
}
class O2 {
public void iWorkForO2() {
System.out.println(« Hi, I work for O2");
}
}
public class TestVector {
public static void main(String[] args) {
Vector v = new Vector() ; // Before Java 5
v.addElement(new O2());
if (v.elementAt(0) instanceof O1)
((O1)v.elementAt(0)).iWorkForO1();
if (v.elementAt(1) instanceof O2)
((O2)v.elementAt(1)). iWorkForO2();
}
}

6
A Class with a Universal Competence
Introduction

public class TestVector2 {


public static void main(String[] args) {
Vector<O1> v = new Vector<O1>(); // Since Java 5
v.add(new O1());
Cloning Objects

// « v.add(new O2()); » is no more possible


v.elementAt(0).iWorkForO1(); // no need for casting !!!!
}
}

Certainly, if casting is no longer necessary, it becomes impossible to use the same


vector for objects of different types (unless they are derived from the same
superclass). In our example, it is no longer possible to insert objects of classes O1 and O2
into the same Vector.

In the end of this course, we will explain how the introduction of generics in Java (as in
C#) has made it possible to type Vector according to the type of objects one wants to
install in it.
7
Breaking Down the Object class.
Introduction

public class Object {

public final native Class getClass();


public native int hashCode();
// more attributes

public boolean equals(Object obj) {


Cloning Objects

return (this == obj);


}

protected native Object clone() throws CloneNotSupportedException;

public String toString() {


return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
// more methods

Thus, the presence of the word "native" in the declaration of methods indicates that they
are written in another programming language, for reasons of optimization or intimate
proximity to the processor's operation, usually C or C++.

8
Breaking Down the Object class.
Introduction

public class Object {

public final native Class getClass();


public native int hashCode();
// more attributes

public boolean equals(Object obj) {


Cloning Objects

return (this == obj);


}

protected native Object clone() throws CloneNotSupportedException;

public String toString() {


return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
// more methods

We have already mentioned the ToString() method, through which the object introduces itself while providing
information about its class. Methods like GetType() in C# and GetClass() in Java also offer a form of introspection
where the object itself can inform the manipulator about the nature of its class and, thereby, provide all desired
information about the methods or attributes characterizing that class. Thus, it is possible to create a new object,
anotherObject, from an existing object, anObject, using the simple instruction:

Object anotherObject = anObject.getClass().newInstance(); // In Java

This allows for the creation of a new object based on an existing one. 9
Breaking Down the Object class.
Introduction

We can find the same methods in C# as well:


public static bool Equals (Object objA , Object objB)
Cloning Objects

public virtual bool Equals (Object obj)


public virtual int GetHashCode () public Type GetType()
public static bool ReferenceEquals(Object objA, Object objB)
public virtual string ToString() protected object MemberwiseClone()

10
Breaking Down the Object class.
Introduction

The `object` class in Python, unlike Java and C#, needs to be explicitly inherited if
one wishes to retrieve certain functionalities. It is also characterized by a set of universally
Cloning Objects

competent methods such as `__init__` for constructing any object and `__new__` for
constructing it from an existing object. We have already seen the `__str__` method, which
provides information at runtime about the dynamic typing of the object. Any subclass of
`object` can redefine these methods.

11
Breaking Down the Object class.
Introduction

public class Object {

public final native Class getClass();


public native int hashCode();
// more attributes

public boolean equals(Object obj) {


Cloning Objects

return (this == obj);


}

protected native Object clone() throws CloneNotSupportedException;

public String toString() {


return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
// more methods

Back to the `Object` class in Java. There are two universal methods that are of particular interest to us.
Firstly, the `equals(Object o)` method, which is used to test the equality of two objects. In Java, it is
called on the first object to compare it to the second. It can be called in a similar manner in C# or by
passing the two objects to compare as arguments (in the latter case, it legitimately becomes static).
The second method is `clone()`, which, in Java, is used to duplicate an object.

12
Equality test of two objects
Introduction

Java code to experiment with the equals(Object o) method


In the following initial program, we code our usual classes, O1 and O2. The class O2 has just one integer
attribute, while the class O1 has an additional attribute of reference type pointing to O2. We then create
Cloning Objects

three O2 objects and two O1 objects whose equality we will test. Initially, several instructions will be
commented out to disable them.

13
Equality test of two objects
Introduction

class O1 { class O2 {
private int o1Attribtute; private int o2Attribtute;
private O2 o2Link; public class Test {
public static void main(String[] args) {
public O2(int o2Attribtute) { O2 o2 = new O2(5);
public O1(int o1Attribtute, O2 o2Link) { this.o2Attribtute = o2Attribtute; O2 anotherO2 = new O2(5);
this.o1Attribtute = o1Attribtute; } O2 aThirdO2 = new O2(10);
this.o2Link = o2Link; aThirdO2 = o2;
}
Cloning Objects

O1 o1 = new O1(10, o2);


public int getAttribut() { O1 anotherO1 = new O1(10, anotherO2);
return o2Attribtute; if (o2 == anotherO2) /* Testing references equality */
/* } System.out.println("o2 and anotherO2 have the same reference");
* The method we are insterested in /* if (o2.equals(anotherO2)) /*
*/ @Override * Without redefinition, it will only test the equality of references,
@Override public boolean equals(Object object) { after redefinition: tests the state as well.
public boolean equals(Object object) { if (this == object) { */
if (this == object) { return true; System.out.println("o2 and unAutreO2 have the same state");
return true; /* renvoie true si les objets sont les mêmes }*/else { if (o2 == aThirdO2)
} else { if (object instanceof O2) { System.out.println("o2 and aThirdO2 have the same reference");
if (object instanceof O1) { O2 anotherO2 = (O2) object; if (o2.equals(aThirdO2))
O1 anotherO1 = (O1) object; /* effectue un casting */ if (o2Attribtute == anotherO2.o2Attribtute) System.out.println("o2 and aThirdO2 have the same state");
if ((o1Attribtute == anotherO1.o1Attribtute) return true; if (o1 == anotherO1)
&& (o2Link.getAttribut() == anotherO1.o2Link.getAttribut()))
else{ System.out.println("o1 and unAutreO1 have the same reference");
return true; return false; if (o1.equals(anotherO1))
} else { } System.out.println("o1 and unAutreO1 have the same state");
return false; } }
} return false; }
} }
} */
return false; }
}
}

In the first instance, we have disabled the redefinition of the equals method in the
O1 and O2 classes. Here is the result of the code in the absence of this
redefinition:

Result:

o2 and aThirdO2 have the same reference. 14


Equality test of two objects
Introduction

Given this result, we understand the default operation of the `equals()` method, inherited from the
`Object` class. Without redefinition, this method behaves exactly like the double equals `==` logical
equality operation from C++ (not to be confused with the simple `=` assignment operation).
Cloning Objects

By default, equality is based on references, meaning the addresses of the objects. If the references
are equal, it indicates that they point to the same object, and thus equality is confirmed.

This reference equality test becomes valuable when the program's complexity reaches a point where, at
certain code stages, it is necessary to verify that two references continue to point to the same object. This
frequently occurs when references are lost in vast vectors or arrays.

15
Equality test of two objects
Introduction

However, what we would like is to extend this equality to objects that, although located in
different memory areas, possess the same state, i.e., attributes with the same values.
Cloning Objects

When the program states “o1 and anotherO1 have the same state," it is correct, but it does not provide
much information since it refers to the same object in memory. Yet, two objects of the same class
characterized by the same state could legitimately be considered equal, regardless of their location
in memory.

16
Equality test of two objects
Introduction

Therefore, you could keep the double equals == for reference equality testing and redefine the
equals() method for state equality testing. This method is ready to be redefined, as follows:

@Override
Cloning Objects

public boolean equals(Object object) {


if (this == object) {
return true; /* renvoie true si les objets sont les
mêmes */
} else {
if (object instanceof O1) {
O1 anotherO1 = (O1) object; /* effectue un
casting */
if ((o1Attribtute == anotherO1.o1Attribtute)
&& (o2Link.getAttribut() ==
anotherO1.o2Link.getAttribut())) {
return true;
} else {
return false;
}
}
}
return false;
}

First, it checks whether it is indeed the same object. If not, it tests whether these two objects are
derived from the same class. Finally, in the affirmative case, it compares the values of the attributes
one by one. 17
Equality test of two objects
Introduction

This redefinition of the two `equals()` methods in both classes was already present in comments. If you
remove the comment markers and execute the program, you obtain:
Cloning Objects

Result:
o2 and anotherO2 have the same state
o2 and aThirdO2 have the same reference
o2 and aThirdO2 have the same state
o1 and anotherO1 have the same state

This demonstrates that, with the redefined `equals()` method, the equality testing considers the state of
objects, allowing for a more meaningful comparison.

18
Cloning Objects
Introduction

Java requires some additions to be able to clone an object.


Cloning Objects

Through the implementation of a specific interface, it is necessary to


declare first that both classes O1 and O2 can be cloned.

Note: Make sure to check the attached source code in order to


understand the next slides.

19
Cloning Objects
Introduction

This addition is a simple label affixed to both classes, necessary during the
execution of cloning, performed by a native method in Java, hence prone
Cloning Objects

to potential issues.

Indeed, since cloning can fail and, as you observe in the signature of the
clone() method, may throw an exception, Java obliges you to anticipate
and handle this exception. Once these additions are made, calling the clone()
method of the Object class results in creating a copy of the object,
attribute by attribute.

20
Cloning Objects
Introduction

As the result of the code indicates, this poses no problem for the `O2` class because it is sufficient to
duplicate the value of its sole attribute and set it in the clone.
Cloning Objects

The redefinition of the `clone()` method in the `O2` class is, in fact, limited to invoking the version from
the `Object` class. However, since this method has a `protected` access level in the `Object` class, you
are forced to override it and declare it as `public` in the `O2` class to use it (encapsulation can only
weaken in restriction when methods are overridden in subclasses).

The presence of this `protected` access is again an encouragement from Java to better control the use of
cloning by recalling the original method.

21
Cloning Objects
Introduction

For O1 however, two solutions are available. Either you opt for a shallow copy of all attributes of the O1
object into a new object, referred to in the code as aThirdO1. In this case, concerning the attribute in O1
that refers to the O2 object, the new O1 object, a clone of the original, will share the value of this attribute
Cloning Objects

and simply start referencing the same O2 object.

However, it may seem preferable that, similar to the cloning of the O1 object, you also clone all attributes
referenced by this object.

22
Cloning Objects
Introduction

Once again, cloning could propagate recursively from reference to reference, aiming to reproduce,
starting from a initial object, the entire relational network in which it is embedded. This is the option
chosen by the code here, which adds as a reference attribute of the new object O1, a clone of that
Cloning Objects

attribute.

To illustrate this mechanism of deep cloning, at the end of the program, we modify the attribute of the O2
object pointed to by the aThirdO1 object. If the O2 object were pointed to twice by both O1 objects, the
result of the comparison test would be different. Therefore, there are indeed two distinct O1 objects and
two distinct O2 objects.

23

You might also like