Java 的API(API: Application(应用) Programming(程序) Interface(接口))
Java API就是JDK中提供给我们使用的类,这些类将底层的代码实现封装了起来,我们不需要关心这些类是如何实现的,只需要知道这些类如何使用即可。
Object类概述
Object类是Java语言中的根类,即所有类的父类。它中描述的所有方法子类都可以使用。所有类在创建对象的时候,最终找的父类就是Object。
equals
equals方法,用于比较两个对象是否相同,它其实就是使用两个对象的内存地址在比较
public class Person { private String name; private int age; public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
public class Test { public static void main(String[] args) { Person p1 = new Person("张三",12); Person p2 = new Person("张三",12); System.out.println(p1); System.out.println(p2); System.out.println(p1.equals(p2)); } }
String将equals方法重写
public class Test { public static void main(String[] args) { String str = "abc"; String str1 = "abc"; System.out.println(str.equals(str1)); } }
自定义类的重写
public class Person extends Object{ private String name; private int age; public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } //对equals方法重写 public boolean equals(int age) { if(this.age ==age) { return true; } return false; } }
public class Test { public static void main(String[] args) { Person p1 = new Person("张三",12); Person p2 = new Person("张三",12); System.out.println(p1); System.out.println(p2); System.out.println(p1.equals(p2.getAge())); } }
toString
toString方法返回该对象的字符串表示,其实该字符串内容就是对象的类型+@+内存地址值。
public class Person { private String name; private int age; public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
public class Test { public static void main(String[] args) { Person p1 = new Person("张三",12); Person p2 = new Person("张三",12); System.out.println(p1.toString()); System.out.println(p2.toString()); } }
在ArrayList和String中toString方法已经重写不再举例
自定义类的重写
public class Person { private String name; private int age; public String toString() { return "Person [age=" + age + "]"; } public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
public class Test { public static void main(String[] args) { Person p1 = new Person("张三",12); Person p2 = new Person("张三",12); System.out.println(p1.toString()); } }