JAVA面向对象高级一:继承子类方法中访问其他成员 子类构造器的特点 子类构造特点的应用场景
1.在子类方法中访问其他成员(成员变量,成员方法),就依照就近原则。
2.子类构造器的特点
package com.itheima.子类访问成员变量; public class F { public F(String a,int b){ System.out.println("===父类的无参构造器执行了==="); } } package com.itheima.子类访问成员变量; public class Z extends F{ public Z(){ super("2",2);//默认存在的 System.out.println("===子类的无参构造器执行了==="); } public Z(int z){ super("2",2);//默认存在的 System.out.println("===子类的无参构造器执行了==="); } } package com.itheima.子类访问成员变量; public class Test { public static void main(String[] args) { //子类构造器的特点:子类的全部的构造器, // 都会先调用父类的构造器,在执行自己 //若父类无无参构造器,子类构造器则会都报错 Z z =new Z(); Z z1 =new Z(2); } }
子类构造特点的应用场景:
package com.itheima.子类访问成员变量; public class Test { public static void main(String[] args) { Teacher teacher=new Teacher("lisi",36,"java"); } } class Teacher extends People{ private String skill; public Teacher(String name,int age,String skill){ super(name,age); this.skill=skill; } public String getSkill() { return skill; } public void setSkill(String skill) { this.skill = skill; } } class People{ private String name; private int age; public People() { } public People(String name, int age) { 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; } }
this()调用兄弟构造器:
任意类的构造器中,是可以通过this(..)去调用该类的其他构造器的 this()与super()不能同时出现在一个类里
package com.itheima.子类访问成员变量; public class Test { public static void main(String[] args) { Student student=new Student("lisi",26,"zjilidun"); Student student1=new Student("lisi",26); } } class Student{ private String name; private int age; private String schoolName; public Student(String name,int age) { this(name,age,"黑马程序员"); } public Student() { } public Student(String name, int age, String schoolName) { this.name = name; this.age = age; this.schoolName = schoolName; } 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 String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } }
总结: