Some basic knowledges about the class Object (1)

Some basic knowledges about the class Object (1)

 

Let's talk about the java.lang.Object. We've known that the class Object is the root of all java class. Just because of that, being familiar with the class Object would help us use more and useful basic functions of our code. Look at the methods. First is the clone(), so we have the code like this,

-----------------------------------------------

public class SubClass {

public int a;

public int b;

public SubClass(int a, int b) {

this.a = a;

this.b = b;

}

public static void main(String[] args) throws CloneNotSupportedException {

SubClass fo = new SubClass(1, 2);

SubClass fo2 = (SubClass) fo.clone();

}

}

--------------------------------------------------

Look in you'll find that the clone() method are there, but it just return the Object type, you have to add cast. If you often use the clone() method, for convient, you'd better override this method, like those code do below.

---------------------------------------------------

public class SubClass {

public int a;

public int b;

public SubClass(int a, int b) {

this.a = a;

this.b = b;

}

public SubClass clone() {

return this;

}

public static void main(String[] args) {

SubClass fo = new SubClass(1, 2);

SubClass fo2 = fo.clone();

}

}

---------------------------------------------------

By the way, when do clone, we often come with another operation: judge the equality. Two ways to support this, one is equals(), another method of Object, the other is operator == . But there exists confusion. First, when two objects A and B are of primitive type, then if they has the same value, you should use operator == to judge the equality. When they aren't the primitive ones, if they are references of the same object, A.equals(B) returns true, (A == B) returns true. If they has the same value but references of different objects, then both return false. 

Another useful method of class Object is toString(). When you want to print out the related info of the object, just overrides this method. This method is automatically called when you use codd System.out.println(). 

---------------------------------------------------

public class SubClass {

public int a;

public int b;

public SubClass(int a, int b) {

this.a = a;

this.b = b;

}

public String toString() {

return "a : " + this.a + ", b : " + this.b;

}

public static void main(String[] args) {

SubClass sc = new SubClass(1, 2);

System.out.println(sc);

}

}

out>>a : 1, b : 2

你可能感兴趣的:(object,String,equals,basic,Class,Primitive)