生成一个Shape类:
package com.qt;
public abstract class Shape {
public abstract float permiter();
public abstract float area();
}
生成一个子类Circle类
package com.qt;
public class Circle extends Shape {
float r;
//构造函数,传入半径r
public Circle(float inpr){
r=inpr;
}
@Override
public float permiter() {
// TODO Auto-generated method stub
float per=(float)(Math.PI*2*r);
System.out.println("圆形的周长为:"+ per);
return per;
}
@Override
public float area() {
// TODO Auto-generated method stub
float area=(float)(Math.PI*r*r);
System.out.println("圆形的面积为:"+ area);
return area;
}
}
生成一个子类Rectangle类
package com.qt;
public class Rectangle extends Shape {
float a,b;
//构造函数,传入矩形的长和宽
public Rectangle(float inpa,float inpb){
a=inpa;
b=inpb;
}
@Override
public float permiter() {
// TODO Auto-generated method stub
float per=(a+b)*2;
System.out.println("矩形的周长为:"+ per);
return per;
}
@Override
public float area() {
// TODO Auto-generated method stub
float area=a*b;
System.out.println("矩形的面积为:"+ area);
return area;
}
生成一个含有main函数的类Initial类
package com.qt;
import java.util.Scanner;
public class Initial {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
System.out.println("请输入圆形半径");
float r=input.nextFloat();
System.out.println("请输入矩形长");
float a=input.nextFloat();
System.out.println("请输入矩形宽");
float b=input.nextFloat();
Shape S=new Rectangle(a,b);
S.area();
S.permiter();
Shape S1=new Circle(r);
S1.area();
S1.permiter();
}
}
热门评论
不错,入门用!~~~)