Java-处理对象

处理对象

1.打印对象和toString方法

都是Object中定义的方法,而所有的类都是继承Object,所以所有对象都有这个方法。

比如System.out.print(xx)中,括号里“xx“不是String类型的话,就自动调用xx的toString方法。

class Person{
    private String name;
    public Person(String name){
        this.name=name;
    }
}
public class PrintObject{
    public static void main(String[] args)
    {
        Person p=new Person("abc");
        System.out.println(p);
        System.out.println(p.toString());
    }
}

输出:Person@15db9742
Person@15db9742

因为System.out的println()方法只能在控制台输出字符串,而Person实例是在内存中的对象.
Object类提供的toString方法总是返回该对象实现类的“类名+@+hashCode”值,这个值不能实现真正的自我描述功能,需要重写实现。

class Apple
{
    private String color;
    private Double weight;
    public Apple{}
    public Apple(String color,Double weight)
    {
        this.color=color;
        this.weight=weight;
    }
    public String toString(){
        return "the color is:"+color+",the weight is:"+weight;
    }
}
public class toStringTest{
    public static void main(String[] args)
    {
        Apple a = new Apple("red",3.44);
        System.out.println(a);
    }
}

这个时候输出的结果应该是 the color is red,the weight is 3.44

一般重写toString()方法总是返回该对象令人感兴趣的信息所组成的字符串。通常可返回如下格式的字符串:

类名[field1=值1,field2=值2,…]

所以上面的toString()方法可以改为:

public String toString()
{
    return "Apple[color="+color+"weight="+weight+"]";
}

2.==和equals方法

  • ‘==’
    • 如果两个变量是基本常量类型,且都是数值类型,则只要两个变量的值相等,返回true;
    • 如果是两个引用类型变量,只有指向同一个对象的时候才返回true。
  • equals()方法
    • 在比较两个引用类型变量时,与‘==’没有区别
    • 通过重写equals方法实现
    • String已经重写了equals方法,String的equals中,只要两个字符串所包含的字符序列相同,则返回true,否则返回false。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值