7月20日总结

时间:2022-09-04 13:49:56

 构造"Teacher"类,继承“Person”类。
1.增加“职称”(String)属性
2.具有和"Student"类类似的重载构造方法
3.重写"Person"类的info()方法,增加“职称”信息
练习程序:
class Person {
 private String name;
 private String location;
 
 Person(String name) {
  this.name = name;
  location = "beijing";
 }
 Person(String name,String location) {
  this.name = name;
  this.location = location;
 }
 public String info() {
  return
   "name: "+name+
   " locaton: "+location;
 }
}

class Teacher extends Person {
 private String capital;
 
 Teacher(String name,String capital) {
  this(name,"beijing",capital);
 }
 
 Teacher(String n,String l,String capital) {
  super(n,l);
  this.capital = capital;
 }
 
 public String info() {
  return super.info() +"capital" + capital;
 }
}

class Student extends Person {
  private String school;
  Student(String name,
  String school) {
    this(name,"beijing",school);
  }
  Student(String n,String l
  ,String school) {
    super(n,l);
    this.school = school;
  }
  public String info() {
    return super.info()+
   "school: "+school;
  }
}

public class TestTeacher {
  public static void main(String[] args) {
    Person p1 = new Person("A");
    Person p2 = new Person("B","shanghai");
    Student s1 = new Student("C","S1");
    Student s2 = new Student("C","shanghai","S2");
    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());
    
  }

}


从SUN公司网站下载API查询文档。
Object类,所有java类 的根基类
如果在类的声明中未使用extends关键字指明其基类,则默认基类为Object类。
Object提供空的构造方法 Object(),系统自动找,防止报错。
Object提供了一系列方法,clone(),复制  equals(),相等
finalize(),回收之前垃圾收集器调用finalize(),把打开的资源关闭 较少使用。
getClass(),返回编译的对象 常用。
hashCode(),找到在内存中的位置。
toString(),返回代表这个对象的一个字符串。描述当前对象的有关信息。
toString() 练习程序:
API文档中 建议所有class调用toString()时要重写例如:public String toString()
public class TestToString {
 public static void main(String[] args) {
  Dog d = new Dog();
  System.out.println("d:=" + d.toString());
 }
}

class Dog {
 public String toString() {
  return "I'm a cool Dog!";
 }
}