以富二代和富一代刷卡为例说明类的继承的必要性
两段代码存在大量的重复,代码冗余需要避免,对开发也不利。
引入类的继承
package classq;
public class Rich {
protected String name;
protected int age;
protected String sex;
public Rich(int age,String name,String sex) {
//形参与成员名字重名,用 this 来区分:
this.age=age;
this.name=name;
this.sex=sex;
}
public void shuaKa()
{
System.out.println("喜刷刷,喜刷刷。。。");
}
}
package classq;
public class Rich1st2 extends Rich{
public Rich1st2(int age,String name,String sex) {
super(age,name,sex);//调用父类构造函数
}
public void shuaKa(){
System.out.println(this.name+"掏出自己的卡");
super.shuaKa();//调用父类放大
}
}
package classq;
public class Rich2nd2 extends Rich{
public Rich2nd2(int age,String name,String sex) {
super(age,name,sex);//调用父类构造函数
}
public void shuaKa(){
System.out.println(this.name+"掏出爸爸的卡");
super.shuaKa();//调用父类放大
}
}
package classq;
public class RichMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
Rich A = new Rich(18,"cma","男");
A.shuaKa();
A=new Rich2nd2(18,"cma","男");
A.shuaKa();
A=new Rich1st2(18,"cma","男");
A.shuaKa();
}
}