public class TestTeacher {
public static void main(String[] args) {
Person p1 = new Person("A");
Person x = new Person("f"); /
Person p2 = new Person("B","shanghai");
Person p3 = new Person("A");
Student s1 = new Student("C","S1");
Student s2 = new Student("C","shanghai","S2");
System.out.println(p1.equals(p3));
System.out.println(p1==p3); //验证类中equals的重写的实现
System.out.println("person的toString验证结果是"+x); //验证toString的重写
System.out.println(p1.info());
System.out.println(p2.info());
System.out.println(s1.info());
System.out.println(s2.info());
Teacher t1 = new Teacher("D","Professor");
System.out.println(t1.info());
}
}
//创建Person类
class Person {
//定义成员变量
private String name;
private String location;
//Person构造方法
Person(String name) {
this.name = name;
location = "beijing";
}
//Person构造方法重载
Person(String name,String location) {
this.name = name;
this.location = location;
}
//Person普通方法
public String info() {
return "name:"+name+"location"+location;
}
//Person重写 equals方法
public boolean equals(Object obj) {
if(obj == null) return false;
else {
if(obj instanceof Person) {
Person p = (Person)obj;
if(this.name == name && this.location == location) {
return true;
}
}
}
return false;
}
//Person重写toString方法
public String toString() {
return "I'm a cool Person";
}
}
//子类class继承父类定义
class Teacher extends Person {
private String capital; //定义成员变量
//Teacher构造方法
Teacher(String name,String capital) {
this(name,"beijing",capital);
}
//Teacher构造方法重载
Teacher(String n,String l,String capital) {
super(n,l);
this.capital = capital;
}
//Teacher普通方法
public String info() {
return super.info()+"capital:"+capital;
}
}
//class继承基类
class Student extends Person{
private String school;
//student构造方法
Student(String name,String school) {
this(name,school,"beijing");
}
//student构造方法重载
Student(String n,String l,String school) {
super(n,l);
this.school = school;
}
//普通方法
public String info() {
return super.info()+"school: "+school;
}
}