慕慕3418381
2018-08-20 21:05
父类
package project55;
public abstract class Shape {
public abstract void c(int a,int b,int r);
public abstract void s(int a,int b,int r);
}
矩形
package project55;
public class Rectangle extends Shape {
@Override
public void c(int a,int b,int r) {
// TODO Auto-generated method stub
System.out.println("矩形周长:"+(a+b)*2);
}
@Override
public void s(int a,int b,int r) {
// TODO Auto-generated method stub
System.out.println("矩形面积:"+a*b);
}
}
圆形
package project55;
public class Circle extends Shape {
double π=3.14;
@Override
public void c(int a,int b,int r) {
// TODO Auto-generated method stub
System.out.println("圆形的周长:"+π*r*2);
}
@Override
public void s(int a,int b,int r) {
// TODO Auto-generated method stub
System.out.println("圆形的面积:"+π*r*r);
}
}
Initail函数
package project55;
import java.util.Scanner;
public class Initail {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
System.out.print("请输入矩形的长a:");
int a=input.nextInt();
System.out.print("请输入矩形的宽b:");
int b=input.nextInt();
System.out.print("请输入圆形半径r:");
int r=input.nextInt();
Shape shape1=new Rectangle();
shape1.c(a,b,r);
shape1.s(a,b,r);
Shape shape2=new Circle();
shape2.c(a,b,r);
shape2.s(a,b,r);
}
}
结果
请输入矩形的长a:4
请输入矩形的宽b:5
请输入圆形半径r:6
矩形周长:18
矩形面积:20
圆形的周长:37.68
圆形的面积:113.03999999999999
你的方法参数写错了。正方形的参数传两个,圆形的传一个就可以了。main方法中,调用类方法时,用相应的子类去声明对象,调用本类的方法。一下是我的代码,可运行
package j2ee;
import java.util.Scanner;
public class HelloWord{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入矩形的长a:");
int a = input.nextInt();
System.out.print("请输入矩形的宽b:");
int b = input.nextInt();
System.out.print("请输入圆形的半径r");
int r = input.nextInt();
rectangle s1 = new rectangle();
s1.c(a,b);
s1.s(a,b);
circle s2 = new circle();
s2.c(r);
s2.s(r);
}
}
package j2ee;
public abstract class shape {
public void r(){};
public void s(){};
}
package j2ee;
import java.util.Scanner;
public class rectangle extends shape {
public void c(int a,int b){
System.out.println(2*(a+b));
}
public void s(int a,int b){
System.out.println(a*b);
}
}
package j2ee;
public class circle extends shape {
double π=3.14;
public void c(int r){
System.out.println(2*π*r);
}
public void s(int r){
System.out.println(π*r*r);
}
}
小白的意见,错了请见谅..
可以先选择要计算的图形形状,用switch判断下,然后创建相应的实例...
Java入门第二季 升级版
530559 学习 · 6091 问题
相似问题