public class Person {
}
等价于
public class Person extendsObject {
}
定义Person类,Person类中有私有成员变量名称(name)、年龄(age),定义一个有参构造器用于初始化成员变量,重写toString方法返回用户信息(包括姓名和年龄);定义一个测试类,在测试类中实例化Person对象并且调用Person对象的toString方法,在控制台输出用户信息
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "我叫" + name + "几年" + age + "岁了"; } } public class Test { public static void main(String[] args) { Person p = new Person("李雷", 18); String info = p.toString(); System.out.println(info); } }
只要猫的颜色、高度和体重相同就认为是同一只猫
public class TestEquals { public static void main(String[] args) { Cat c1 = new Cat(1, 2, 3); Cat c2 = new Cat(1, 2, 6); System.out.println(c1 == c2); System.out.println(c1.equals(c2)); String s1 = new String("hello"); String s2 = new String("hello"); System.out.println(s1 == s2); System.out.println(s1.equals(s2)); } } class Cat { int color; int height, weight; public Cat(int color, int height, int weight) { this.color = color; this.height = height; this.weight = weight; } public boolean equals(Object obj) { if(obj == null) return false; else { if(obj instanceof Cat) { Cat c = (Cat)obj; if(c.color == this.color && c.height == this.height && c.weight == this.weight) { return true; } } } return false; } }定义一个Dog类,Dog类中有成员变量名称(name)、年龄(age),定义一个有参构造器用于初始化成员变量,定义一个Dog数组,数组中有7个元素,分别是:金毛1岁,萨摩耶1岁,博美2岁,金毛2岁,金毛1岁,博美3岁,博美1岁;现重写Dog类中的equals方法,判断:只要Dog的名称和年龄相同,则表示是同一条狗。编写一个测试类,控制台输出相同的金毛狗的个数
+
public class Dog { public String name; public int age; public Dog(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object obj) {// Object obj = dog; if(obj instanceof Dog){ Dog dog = (Dog) obj; if(dog.name.equals(this.name) && dog.age == this.age){ return true; } } return false; } } @Test public void test(){ Dog[] arr = new Dog[7]; Dog dog1 = new Dog("金毛", 1);// Dog dog2 = new Dog("薩摩耶", 1); Dog dog3 = new Dog("博美", 2); Dog dog4 = new Dog("金毛", 2); Dog dog5 = new Dog("金毛", 1);// Dog dog6 = new Dog("博美", 3); Dog dog7 = new Dog("博美", 1); arr[0] = dog1; arr[1] = dog2; arr[2] = dog3; arr[3] = dog4; arr[4] = dog5; arr[5] = dog6; arr[6] = dog7; int cnt = 0; for(int i=0; i<arr.length; i++){ for(int j=0; j<arr.length; j++){ if(arr[i].equals(arr[j])){ cnt ++; } break; } } System.out.println("相同狗的个数是:" + cnt); }