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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值