1、先写爷爷类
package com.wyq.study;
public class B {
private String name;
private int 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;
}
public B(String name, int age) {
super();
this.name = name;
this.age = age;
System.out.println("B的实参构造");
}
public B() {
super();
System.out.println("B的无参构造");
}
}
2、再写父亲类
package com.wyq.study;
public class C extends B{
private String job;
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public C(String name, int age, String job) {
super(name, age);
this.job = job;
System.out.println("这里是C的带参构造。");
}
public C() {
super();
System.out.println("这里是C的无参构造。");
}
public void say(String place){
System.out.println("C正在"+place+"地方说话。"+"他的工作是"+job);
}
}
3、接着写孙子类
package com.wyq.study;
public class D extends C{
private String course;
private int teachAge;
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public int getTeachAge() {
return teachAge;
}
public void setTeachAge(int teachAge) {
this.teachAge = teachAge;
}
public D(String name, int age, String job,String course, int teachAge) {
super(name, age, job);
this.course = course;
this.teachAge = teachAge;
System.out.println("这里是"+name+"\t"+age+"\t"+job+"\t"+course+"\t"+teachAge);
}
public D() {
super();
System.out.println("D的无参构造");
}
public void speak(String home,int age){
System.out.println("参数为:"+course+"\t"+age+"\t"+this.getCourse()+"\t"+this.getCourse()+"\t"+this.getName()+"\t"+this.getAge());
System.out.println("以下是超类测试");
System.out.println("这里是超类的测试"+super.getAge()+"\t"+super.getName()+"\t"+super.getJob()+"\t");
}
}
4、最后测试
package com.wyq.study;
public class testD {
public static void main(String[] args) {
D d = new D("张三",10,"程序员","计算机",15);
d.speak("北京市", 10);
}
}
5、总结
1)先写父类
2)再写子类,子类继承父类,创建无参和有参构造,初始化属性
3)再写孙子类,也是继承的关系,创建无参和有参构造,初始化属性,调用父类属性使用super关键字