package java_5_25;
/*
* @Description:
* @Author: Rainbow
* @version:v1.0
* @date:2021年5月25日下午3:12:10
*
* 抽象方法(abstract method):通过 abstract 类型修饰符来创建的没有内容的抽象方法。
* 1. abstract 修饰符只能用于实例方法,不能用于static 方法或构造函数。 *
* 2.有时需要创建一个这样的超类:该超类只定义一个为所有子类共享的一般形式。至于细节
* 则交给每个子类去填充。
* 3.当子类继承抽象类时,它必须实现超类中的所有抽象方法。否则也必须将子类定义为抽象类。
* 4.包含一个或多个抽象方法的类必须通过在其class 声明前添加abstract 修饰符,来将其
* 声明为抽象类。抽象类不定义完整的实现方式,没有自己的对象,因此任何使用new 创建
* 抽象类对象的尝试都会导致编译时的错误。
*/
// 创建抽象类
abstract class TwoDShape{
private double width;
private double height;
private String name;
TwoDShape(){
width=height=0.0;
name="none";
}
TwoDShape(double w,double h,String n){
width=w;
height=h;
name=n;
}
// 构造长和宽均相等的对象
TwoDShape(double x,String n){
width=height=x;
name=n;
}
// construct an object from an object 从一个对象构造一个对象
TwoDShape(TwoDShape ob){
width=ob.width;
height=ob.height;
name=ob.name;
}
// Accessor methods for width and heigth
double getWidth() {return width;}
double getHeight() {return height;}
String getName() {return name;}
void setWidth(double w) {width=w;}
void setHeight(double h) {height=h;}
void showDim() {
System.out.println("width and heigth are "+width+" and "+height);
}
//把area()声明为抽象方法
abstract double area();
}
// subclass 子类 Triangle
class Triangle extends TwoDShape{
private String style;
Triangle(){
super();
style="none";
}
Triangle(String s,double w,double h){
super(w,h,"triangle");
style=s;
}
Triangle(double x){
super(x,"Triangle");
style="filled";
}
Triangle(Triangle ob){
super(ob);
style=ob.style;
}
double area() {
return getWidth()*getHeight()/2;
}
void showStyle() {
System.out.println("Triangle is "+style);
}
}
// subclass 子类 Rectangle
class Rectangle extends TwoDShape{
Rectangle(){
super();
}
Rectangle(double w,double h){
super(w,h,"rectangle");
}
Rectangle(double x){
super(x,"rectangle");
}
Rectangle(Rectangle ob){
super(ob);
}
boolean isSquare() {
if(getWidth()==getHeight()) return true;
else
return false;
}
double area() {
return getHeight()*getWidth();
}
}
public class abstractClass {
public static void main(String[] args) {
TwoDShape shapes[] =new TwoDShape[4];
shapes[0]=new Triangle("outlined",8.0,12.0);
shapes[3]=new Triangle(10);
shapes[1]=new Rectangle(7.0);
shapes[2]=new Rectangle(10,4);
for(int i=0;i<shapes.length;i++) {
System.out.println("Object is "+shapes[i].getName());
System.out.println("Area is "+shapes[i].area());
System.out.println();
}
}
}
抽象方法abstract method
最新推荐文章于 2022-02-15 21:22:11 发布