java学习笔记2--面向对象编程( 七 )


public boolean equals(Object o) {//1.比较两个对象的内存地址if (this == o) return true;//2.判断o是否为空,不为空再比较两者的类型是否一致if (o == null || getClass() != o.getClass()) return false;//3.向下转型Test1 test1 = (Test1) o;//4.比较两者的属性是否相等//对于引用数据类型的属性,要先判断对象是否为空,不为空才能调用equals方法return age == test1.age && Objects.equals(name, test1.name);}public static boolean equals(Object a, Object b) {return (a == b) || (a != null && a.equals(b));}
18.4 "=="和()的区别18.5 ()练习
int it = 65;float fl = 65.0f;System.out.println(“65和65.0f是否相等?” + (it == fl)); //truechar ch1 = 'A'; char ch2 = 12;System.out.println("65和'A'是否相等?" + (it == ch1));//trueSystem.out.println(“12和ch2是否相等?" + (12 == ch2));//trueString str1 = new String("hello");String str2 = new String("hello");System.out.println("str1和str2是否相等?"+ (str1 == str2));//falseSystem.out.println("str1是否equals str2?"+(str1.equals(str2)));//trueSystem.out.println(“hello” == new java.util.Date()); //编译不通过
18.6 ()方法 18.6.1 类中的定义方法
public String toString() {return getClass().getName() + "@" + Integer.toHexString(hashCode());}
18.6.2 细节
1..out.(对象); 和.out.(对象.());当对象不是null时,两者效果相同;当对象为null时,直接会输出null,调用方法会报空指针异常;
2.像、Date、File、包装类等都重写了类中的()方法,使得在调用()时,返回"实体内容"信息;
3.char[]数组也重写了同方法;
4.自定义类如果重写()方法,当调用此方法时,返回对象的"实体内容".
5.与其它类型数据进行连接操作时,自动调用()方法,对于基本数据类型则是调用包装类的()方法;
18.6.3 举例
public class ToStringTest {public static void main(String[] args) {Customer cust1 = new Customer("Tom" ,21);System.out.println(cust1.toString()); //github4.Customer@15db9742System.out.println(cust1);//github4.Customer@15db9742 ---> Customer[name = Tom,age = 21]String str = new String("MM");System.out.println(str);Date date = new Date(45362348664663L);System.out.println(date.toString()); //Wed Jun 24 12:24:24 CST 3407}}
public void test() {char[] arr = new char[] { 'a', 'b', 'c' };System.out.println(arr);//abcint[] arr1 = new int[] { 1, 2, 3 };System.out.println(arr1);//[I@722c41f4double[] arr2 = new double[] { 1.1, 2.2, 3.3 };System.out.println(arr2);//[D@5b80350b}
19.单元测试 19.1 要求19.2 idea中添加模板
在live-中添加了代码模板,快捷键是test;
19.3 使用
import org.junit.Test;/*** @Description:* @author:zhou* @create: 2022-01-22 16:56*/public class JUnitTest {@Testpublic void testEquals(){System.out.println("123");}@Testpublic void test123(){System.out.println("456");//System.out.println(1/0);}}
20.包装类
包装类是引用数据类型,变量的默认值是null
20.1 8种基本数据类型对应的包装类 基本数据类型包装类
int
byte
Byte
short
Short
long
Long
float
Float
char
20.2 基本数据类型转为包装类
使基本数据类型拥有类的特性(方法,属性),常用自动装箱
int i = 123;//方法1:将基本数据类型当作参数传入Integer构造器Integer n = new Integer(i);System.out.println(n); // 通过println输出时,n和n.toString()的效果相同System.out.println(n.toString());//方法2:通过字符串参数构造包装类对象,字符串中的类型一定要与包装类兼容Integer n1 = new Integer("123");System.out.println(n);Float f = new Float(23.1);System.out.println(f);Double d = new Double("23.1");System.out.println(d);//方法3:自动装箱Integer n2 = 5;System.out.println(n2.toString());