[工学]charp6面向对象高级特性.ppt
文本预览下载声明
public class Timer { int hour,minute,second; public Timer( ) //默认构造方法,此例中不能省略 {} public Timer(int h,int m,int s) //自定义的构造方法 { hour=h; minute=m; second=s; } void showTime() { System.out.println(现在时间是:+hour+:+minute+:+second); } public static void main(String[] args) { Timer t1=new Timer(10,11,12); //调用了自定义的构造方法 t1.showTime(); Timer t2=new Timer( ); //调用了默认构造方法创建实例 t2.showTime(); } } 例: 类继承的作用 class Children extends Parent { int age; //子类自定义的成员变量 Children(String cName,int cAge) //构造方法 { name=cName; //name属性继承自父类Parent age=cAge; } public static void main(String[ ]args) { Children children=new Children(王强,10); System.out.println(子类信息如下:); children.showInfo(); //showInfo()方法继承自父类 } } 【运行结果】 姓名:王强 6.2 继承(变量的覆盖和方法重写) 当子类的成员变量与父类的成员变量同名时,在子类中将隐藏父类同名变量的值,这叫做变量覆盖。 当子类重新定义了和父类同名的方法时,子类方法的功能将会覆盖父类同名方法的功能,这叫做方法“重写”。 方法重写发生在有父子类继承关系,且父子类中的两个同名方法的参数列表和返回值完全相同的情况下。 另外,还需注意下面的两条限制: 1)重写的方法不能比被重写的方法拥有更严格的访问权限; 2)重写的方法不能比被重写的方法产生更多的异常。 例5-19:成员方法重写 例:成员方法重写 class Children extends Parent { String name; //子女姓名 int age; Children(String cName,char cSex,int cAge) //构造方法 { //super(); //默认省略了此语句 name=cName; sex=cSex; age=cAge; } void showInfo() //显示子类实例信息,重写了父类的showInfo()方法 { System.out.println(孩子的姓名:+name); System.out.println(孩子的性别:+sex); System.out.println(孩子的年龄:+age); } public static void main(String[ ]args) { Children children=new Children(王强,M,10); System.out.println(子类信息如下:); children.showInfo(); } } 重写与重载的区别 super关键字的使用 class B1 extends A1 { int a, b; public B1(int x, int y, int a, int b) { super(x, y); // 调用直接父类的构造方法 this.a = a; this.b = b
显示全部