非抽象类的实现方法
package hiwari;
/*
* 设计抽象形状类Shape,包含输出周长的方法;
* 重写输出周长的方法。在主函数中创建圆类(Circle)和长方形类(Rectangle),
* 重写输出周长的方法。在主函数中创建圆类和长方形类对象各3个,
* 将这些对象转换成Shape类型后,用for循环输出各个对象的周长
* */
class Shape {
void printName(){
System.out.println("未知形状");
}
void area()
{
System.out.println("未知面积");
}
}
class Circle extends Shape
{
double r;
void printName()
{
System.out.println("圆形");
}
void area()
{
System.out.println(3.14*r*r);
}
Circle(double a){r=a;}
}
class Rectangle extends Shape
{
double l,h;
void printName()
{
System.out.println("长方形");
}
void area()
{
System.out.println(l*h);
}
Rectangle(double a,double b){l=a;h=b;}
}
public class text {
public static void main(String[] args) {
Shape s[]=new Shape[2];
s[0]=new Circle(2);
s[1]=new Rectangle(2,3);
for(int i=0;i<2;i++)
{
s[i].printName();
s[i].area();
}
}
}
抽象类的实现方法
package hiwari;
/*
* 设计抽象形状类Shape,包含输出周长的方法;
* 重写输出周长的方法。在主函数中创建圆类(Circle)和长方形类(Rectangle),
* 重写输出周长的方法。在主函数中创建圆类和长方形类对象各3个,
* 将这些对象转换成Shape类型后,用for循环输出各个对象的周长
* */
abstract class Shape {
abstract void printName();
abstract void area();
}
class Circle extends Shape
{
double r;
void printName()
{
System.out.println("圆形");
}
void area()
{
System.out.println(3.14*r*r);
}
Circle(double a){r=a;}
}
class Rectangle extends Shape
{
double l,h;
void printName()
{
System.out.println("长方形");
}
void area()
{
System.out.println(l*h);
}
Rectangle(double a,double b){l=a;h=b;}
}
public class text {
public static void main(String[] args) {
Shape s[]=new Shape[2];
s[0]=new Circle(2);
s[1]=new Rectangle(2,3);
for(int i=0;i<2;i++)
{
s[i].printName();
s[i].area();
}
}
}