This example describes the use of object classes in Java. Share to everyone for your reference. Specifically as follows:
1. The object class is the base class for all Java classes
If the extends keyword is not used in the declaration of the class to indicate its base class, the default base class is the object class, ex:
public class person{
~~~~~
}
Equivalent to
public class person extends object{
~~~~~
}
2, the object class Equals method
The ①, object classes are defined as:
public boolean equals (Object obj) method.
Provides logic that defines whether an object is equal.
The ②, Objec equals method is defined as: X.equals (y) returns True if X and Y are applications of the same object, or false.
Some classes provided by ③, J2SDK, such as String,date, override the Equals () method of object, call the Equals method of these classes, X.equals (y), when X and Y refer to the same class object and the property content is equal (not necessarily equal) , returns True otherwise returns false.
④, you can override the Equals () method in the user's custom type as needed.
The instance code is as follows:
public class testequals{public
static void Main (String args[]) {
cat cat1 = new Cat (1,2,3);
Cat Cat2 = new Cat (1,2,3);
System.out.println (CAT1 = = CAT2);
System.out.println (Cat1.equals (Cat2 ));
string S1 = new String ("Hello");
String s2 = new string ("Hello");
System.out.println (S1 = = s2);
System.out.println (s1.equals (S2));
}
class cat{
int color;
int height,weight;
Cat (int color, int height, int weight) {
this.color= color;
this.height = height;
This.weight = weight;
}
public boolean equals (Object obj) {
if (obj = null) return false;
else{
if (obj instanceof cat) {
cat c = (cat) obj;
if (C.color = this.color && c.height = this.height && c.weight = this.weight) {return
true;
}
}
}
return false;
}
}
The results of the operation are shown in the following illustration:
I hope this article will help you with your Java programming.