1 package cn.mooc.student; 2 3 //父类 4 class Person{ 5 //属性 6 private String name; 7 private String gender; 8 private String location; 9 private int age; 10 //构造方法 11 public Person() { 12 System.out.println("Person() run!"); 13 } 14 public Person(String name){ 15 System.out.println("Person(name) run!"); 16 this.name = name; 17 } 18 public Person(String name, String gender, String location, int age) { 19 System.out.println("Person(*) run!"); 20 this.name = name; 21 this.gender = gender; 22 this.location = location; 23 this.age = age; 24 } 25 //方法set get 26 public void setName(String name) { 27 this.name = name; 28 } 29 public String getName(){ 30 return this.name; 31 } 32 public String getGender() { 33 return gender; 34 } 35 public void setGender(String gender) { 36 this.gender = gender; 37 } 38 public String getLocation() { 39 return location; 40 } 41 public void setLocation(String location) { 42 this.location = location; 43 } 44 public int getAge() { 45 return age; 46 } 47 public void setAge(int age) { 48 this.age = age; 49 } 50 51 //方法eat 52 public void eat(Person p){ 53 System.out.println(p.name+" is eatting!"); 54 } 55 //方法toString(对于Object类toString方法的复写) 56 public String toString() { 57 return "Person [name=" + name + ", gender=" + gender + ", location=" 58 + location + ", age=" + age + "]"; 59 } 60 } 61 62 //子类 63 public class Student extends Person { 64 //属性 65 private int credit; 66 private String name; 67 //构造方法 68 public Student(){} 69 public Student(int credit,String name) { 70 super(name); 71 this.credit = credit; 72 System.out.println("Student(*) run"); 73 //this.name = name; 74 //若子类没有父类属性,则默认调用父类空参(此时父类若无空参,就会报错) 75 } 76 //方法get 77 public int getCredit(){ 78 return this.credit; 79 } 80 //方法set 81 public void setCredit(int credit){ 82 this.credit = credit; 83 } 84 //方法study 85 public void study(Student s){ 86 System.out.println(s.getName()+" is studying!"); 87 } 88 //方法toString 89 public String toString(){ 90 return "name="+name+"::credit="+credit; 91 } 92 93 public static void main(String[] args) { 94 Person p1 = new Person("Lily","female","America",20); 95 //Student s1 = (Student) p1; 96 //System.out.println(s1.toString()); 97 //1,ClassCastException父类不能转为子类 98 99 Student s1 = new Student(16,"Luck"); 100 s1.setName("GG");//调用父类的方法改变父类属性,但不影响自身的属性 101 s1.setAge(22); 102 System.out.println(s1.toString()); 103 //2,子类可以调用父类方法,当父类和子类有相同方法时,优先调用子类自己的方法 104 105 p1.toString(); 106 //3,父类不能调用子类方法 107 //综上,子类获取了父类所有的属性和方法,但如果有与自己相同的方法,调用时优先调用自身属性方法 108 } 109 }
Person(*) run!
Person(name) run!
Student(*) run
name=null::credit=16
可以看出.子类的创建伴随着对父类相应构造器的调用
父类相应的构造方法,通过super(parameters)传递到子类