public class Test {
int area = shape.computeArea();
System.out.println("triangle:"+area);
shape = new Rectangle(10,10);
area = shape.computeArea();
System.out.println("rectangle:"+ area);
}
}
abstract class Shape {//使用了abstract关键字修饰的类叫做抽象类,抽象类无法实例化,也就是说不能new出来一个抽象类的对象
class Triangle extends Shape {//在子类继承父类(前提父类是个抽象类)的情况下,那该子类必须要实现父类中所定义的所有抽象方法;否则该子类需要声明成一个abstract class
int width;
int height;
this.height = height;
}
public int computeArea() {
return (width*height) / 2;
}
}
class Rectangle extends Shape {
int width;
int height;
public Rectangle(int width,int height) {
this.width = width;
this.height = height;
}
public int computeArea() {
return width*height;
}
}
public static void main(String[] args) {
int area = shape.computeArea();
System.out.println("triangle:"+area);
shape = new Rectangle(10,10);
area = shape.computeArea();
System.out.println("rectangle:"+ area);
}
}
abstract class Shape {//使用了abstract关键字修饰的类叫做抽象类,抽象类无法实例化,也就是说不能new出来一个抽象类的对象
public abstract int computeArea();//计算形状面积、使用abstract关键字修饰的方法叫做抽象方法,抽象方法只有声明没有实现。
public void change() {//抽象类中也可以包含具体方法
}
//如果一个类中包含了抽象方法,那么这个类一定要声明成abstract class,也就是说,该类一定是抽象类。
}class Triangle extends Shape {//在子类继承父类(前提父类是个抽象类)的情况下,那该子类必须要实现父类中所定义的所有抽象方法;否则该子类需要声明成一个abstract class
int width;
int height;
public Triangle(int width,int height) {//构造方法主要完成变量的初始化
this.height = height;
}
public int computeArea() {
return (width*height) / 2;
}
}
class Rectangle extends Shape {
int width;
int height;
public Rectangle(int width,int height) {
this.width = width;
this.height = height;
}
public int computeArea() {
return width*height;
}
}
本文通过一个具体的Java程序示例介绍了如何使用抽象类和多态来实现不同形状的面积计算。示例中定义了一个抽象类Shape,并派生出Triangle和Rectangle两个子类,每个子类都实现了计算面积的方法。主程序创建这些形状对象并调用它们的计算面积方法,展示多态的实际应用。
1118

被折叠的 条评论
为什么被折叠?



