JAVA 作业 实验名称:接口,继承与多态
2.Shape:
packagecom.test;
publicinterfaceShape{
publicdoublearea();
publicdoubleperimeter();
}
Circle:
packagecom.test;
publicclassCircleimplementsShape{
doubler=5;
doublepi=3.14;
@Override
publicdoublearea(){
returnpi*r*r;
}
@Override
publicdoubleperimeter(){
return2*pi*r;
}
}
Rectangle:
packagecom.test;
publicclassRectangleimplementsShape{
doublea=3;
doubleb=4;
@Override
publicdoublearea(){
returna*b;
}
@Override
publicdoubleperimeter(){
return2*(a+b);
}
}
Triangle:
packagecom.test;
publicclassTriangleimplementsShape{
doublea=4;
@Override
publicdoublearea(){
returna*a;
}
@Override
publicdoubleperimeter(){
return4*a;
}
}
3.
shape:
packagecom.test.abstr;
publicabstractclassShape{
publicdoublearea(){
return0.0;
}
publicdoubleperimeter(){
return0.0;
}
}
Circle:
packagecom.test.abstr;
publicclassCircleextendsShape{
doubler=5;
doublepi=3.14;
publicdoublearea(){
returnpi*r*r;
}
publicdoubleperimeter(){
return2*pi*r;
}
}
Rectangle:
packagecom.test.abstr;
publicclassRectangleextendsShape{
doublea=3;
doubleb=4;
publicdoublearea(){
returna*b;
}
publicdoubleperimeter(){
return2*(a+b);
}
}
Triangle:
packagecom.test.abstr;
publicclassTriangleextendsShape{
doublea=4;
publicdoublearea(){
returna*a;
}
publicdoubleperimeter(){
return4*a;
}
}
Test:
packagecom.test.abstr;
publicclassTest{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
Shapes1=newCircle();
System.out.println(s1.area());
System.out.println(s1.perimeter());
Shapes2=newRectangle();
System.out.println(s2.area());
System.out.println(s2.perimeter());
Shapes3=newTriangle();
System.out.println(s3.area());
System.out.println(s3.perimeter());
}
}
结果:
78.5
31.400000000000002
12.0
14.0
16.0
16.0
4.packagecom.test.four;
publicclassPerson{
Stringname;
publicvoidpay(doublenum){
System.out.println(name+"共花费"+num+"元");
}
}
packagecom.test.four;
publicclassShoppingCart{
publicStringname;
publicdoubleprice;
publicintcount;
}
packagecom.test.four;
publicclassCheckstand{
publicstaticvoidmain(String[]args){
doublecount=0.0;
ShoppingCartsc1=newShoppingCart();
sc1.name="牙膏";
sc1.price=6.5;
sc1.count=1;
count=count+getCount(sc1);
ShoppingCartsc2=newShoppingCart();
sc2.name="香皂";
sc2.price=4.5;
sc2.count=1;
count=count+getCount(sc2);
ShoppingCartsc3=newShoppingCart();
sc3.name="洗衣粉";
sc3.price=16.5;
sc3.count=1;
count=count+getCount(sc3);
Personperson=newPerson();
person.name="小花";
person.pay(count);
}
publicstaticdoublegetCount(ShoppingCartsc){
System.out.println(sc.name+"----"+sc.count+"件"+sc.price*sc.count+"元");
returnsc.price*sc.count;
}
}
结果:
牙膏 ----1件 6.5元
香皂 ----1件 4.5元
洗衣粉 ----1件 16.5元
小花共花费27.5元
个人建议,如果是初学者还是自己多去思考,多去练习,如果以后想从事软件开发方面的,更需要多练多看多想。
多重随机标签