志在指尖
用双手敲打未来

成员变量的隐藏和方法重写

一:成员变量的躲藏
子类承继的办法只能操作子类承继和躲藏的成员变量。子类新界说的办法可以操作子类承继和子类新声明的成员变量,但无法操作子类躲藏的成员变量(需运用super关键字操作子类躲藏的成员变量(下次更新super关键字))。
Goods.java
packagechengyuanbianliangdeyincang;publicclassGoods{publicdoubleweight;publicvoidoldSetWeight(doublew){
weight=w;
System.out.println(“double型的weight=”+weight);
}publicdoubleoldGetPrice(){doubleprice=weight*10;returnprice;
}
}
CheapGoods.java
packagechengyuanbianliangdeyincang;publicclassCheapGoodsextendsGoods{publicintweight;publicvoidnewSetWeight(intw){
weight=w;
System.out.println(“int型的weight=”+weight);
}publicdoublenewGetPrice(){doubleprice=weight*10;returnprice;
}
}
yincang.java
packagechengyuanbianliangdeyincang;publicclassyincang{publicstaticvoidmain(String[]args){
CheapGoodscheapGoods=newCheapGoods();//cheapGoods.weight=198.98;是不合法的,由于子类目标的weight变量已经是int型cheapGoods.newSetWeight(198);
System.out.println(“目标cheapGoods的weight的值是:”+cheapGoods.weight);
System.out.println(“cheapGoods用子类新增的优惠办法核算价格:”+cheapGoods.newGetPrice());
cheapGoods.oldSetWeight(198.987);//子类目标调用承继的办法操作躲藏的double型变量weightSystem.out.println(“cheapGoods运用承继的办法(无优惠核算价格)”+cheapGoods.oldGetPrice());
}
}Java
二:办法重写
1.重写的语法规则
假如子类可以承继父类的某个办法,那么子类就有权力重写这个办法。所谓办法重写,是指子类中界说一个办法,这个办法的类型和父类的办法的类型共同或者是父类的办法的类型的子类型(所谓子类型,是指假如父类的办法的类型是“类”,那么答应子类的重写办法的类型是“子类”),并且这个办法的名字,参数个数,参数的类型和父类的办法完全相同,子类如此界说的办法称作子类重写的办法。
2.重写的目的
重写办法既可以操作承继的成员变量、调用承继的办法,也可以操作子类新声明的成员变量、调用新界说的其他办法,但无法操作被子类躲藏的成员变量和办法。假如子类想运用被躲藏的办法或成员变量,必须运用关键字super(下次更新super用法)。
在下面的比如中,ImportantUniversity是University类的子类,子类重写了父类的enterRule()办法。
University.java
packagefangfachongxie;publicclassUniversity{voidenterRule(doublemath,doubleenglish,doublechinese){doubletotal=math+english+chinese;if(total>=180){
System.out.println(total+”分数到达大学录取线”);
}else{
System.out.println(total+”分数未到达大学录取线”);
}
}
}
ImportantUniversity.java
packagefangfachongxie;publicclassImportantUniversityextendsUniversity{voidenterRule(doublemath,doubleenglish,doublechinese){doubletotal=math+english+chinese;if(total>=220){
System.out.println(total+”分数到达重点大学录取线”);
}else{
System.out.println(total+”分数未到达重点大学录取线”);
}
}
}
Chongxie.java
packagefangfachongxie;publicclassChongxie{publicstaticvoidmain(String[]args){doublemath=62,english=76.5,chinese=67;
ImportantUniversityuniver=newImportantUniversity();
univer.enterRule(math,english,chinese);//调用重写的办法math=91;
english=82;
chinese=86;
univer.enterRule(math,english,chinese);
}
}
运转结果如下:
205.5分数未到达重点大学录取线
259.0分数到达重点大学录取线
3.重写的注意事项
重写父类的办法时,不答应降低办法的拜访权限,但可以进步拜访权限(拜访约束修饰符按拜访权限从高到低的排列次序是public、protected、友爱的、private)。下面的代码中,子类重写父亲的办法w,该办法在父类中的拜访权限是protected等级,子类重写时不答应等级低于protected,例如:
classA{protectedfloatw(floatx,floaty){returnx-y;
}
}classBextendsA{floatw(floatx,floaty){//不合法,由于降低了拜访权限returnx+y;
}
}classCextendsA{publicfloatw(floatx,floaty){//合法,进步了拜访权限returnx*y;
}
}

未经允许不得转载:IT技术网站 » 成员变量的隐藏和方法重写
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载