匿名构造方法的使用以及比较对象的问题
package com.yonge.objectEquals;/** * 目的:1、测试匿名构造方法的使用及作用域 2、对象的比较 * @author wb-gaoy * @version $Id: Test.java,v 0.1 2012-1-10 下午12:04:42 wb-gaoy Exp $ */public class Test { private String str; /** 默认构造方法 */ public Test() { System.out.println("默认构造方法被调用!!"); } /** 带两个String参数的构造方法 */ public Test(String arg0, String arg1) { System.out.println("带参数的构造方法!"); this.str = arg0 + arg1; if (str == (arg0 + arg1)) { System.out.println("str[" + this.str + "]与arg0+arg1[" + arg0 + arg1 + "]相等!!"); } else { System.out.println("str[" + this.str + "]与arg0+arg1[" + arg0 + arg1 + "]不相等!!"); } } /** 匿名构造方法:每次实例化对象的时候,首先会调用此块 */ { System.out.println("匿名构造方法被调用!"); } /** * @param args */ public static void main(String[] args) { Test test = new Test(); Test test1 = new Test("1", ""); String arg0 = "1", arg1 = "1"; if (arg0 == arg1) { System.out.println("arg0[" + arg0 + "]与arg1[" + arg1 + "]对象相等!!"); } else { System.out.println("arg0[" + arg0 + "]与arg1[" + arg1 + "]对象相等!!"); } //给arg0重新赋值 arg0 = "1" + ""; System.out.println("给arg0重新赋值为:" + arg0); if (arg0 == arg1) { System.out.println("arg0[" + arg0 + "]与arg1[" + arg1 + "]对象相等!!"); } else { System.out.println("arg0[" + arg0 + "]与arg1[" + arg1 + "]对象相等!!"); } if ("1" + "" == arg1) { System.out.println("arg0["1" + ""]与arg1[" + arg1 + "]对象相等!!"); } else { System.out.println("arg0[" + arg0 + "]与arg1[" + arg1 + "]对象相等!!"); } //给arg0重新赋值 arg0 = new String("1");//改成arg0 = new String("2")试试 System.out.println("给arg0第二次重新赋值为:" + arg0); if (arg0 == arg1) { System.out.println("arg0[" + arg0 + "]与arg1[" + arg1 + "]对象相等!!"); } else { System.out.println("arg0[" + arg0 + "]与arg1[" + arg1 + "]对象相等!!"); } if (new String("1") == "1") { System.out.println("对象相等"); } else { System.out.println("对象不相等"); } }}
?