⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 planegraphics1.java

📁 这是《Java2程序设计实用教程(第2版)》教材中附带的例题源代码。
💻 JAVA
字号:
//【例3.8】  抽象类与抽象方法。

public abstract class PlaneGraphics1   //平面图形类,抽象类
{
    private String shape;              //形状
    
    public PlaneGraphics1(String shape)//构造方法,不能是抽象方法
    {
        this.shape = shape;
    }

    public PlaneGraphics1()
    {
        this("未知");
    }

    public abstract double area();     //计算面积,抽象方法,分号";"必不可少 

    public void print()                //显示面积,非抽象方法
    {
        System.out.println(this.shape+"面积为 "+this.area());
    }
}

class PlaneGraphics1_ex
{
    public static void main(String args[])
    {
        PlaneGraphics1 g1 = new Rectangle1(10,20);//获得子类对象,长方形
        g1.print();                    //print()不是运行时多态性,其中调用的area()表现运行时多态性

        g1 = new Rectangle1(10);       //正方形
        g1.print();

        g1 = new Ellipse1(10,20);      //椭圆
        g1.print();

        g1 = new Ellipse1(10);         //圆
        g1.print();
    }
}

/*

程序运行结果如下:

长方形面积为 200.0
正方形面积为 100.0
椭圆面积为 628.3185307179587
圆面积为 314.1592653589793

*/



/*

程序正确

1、抽象类也可以不包含抽象方法,此时仍然不能创建对象。例如,

public abstract class Shape             //图形类,抽象类
{
    public void finalize()              //抽象类中可以有析构方法
    {
    }

    public double area()                //计算面积,非抽象方法,必须有方法体
    {
        return 0;
    }

    public void print()
    {
    }
}

2、抽象类中可以包含main方法。例如,

    public static void main(String args[])


程序错误:

1、构造方法不能被声明为抽象方法
    public abstract Shape();            //编译错,modifier abstract not allowed here


2、不能创建抽象类的对象
class Shape1_ex
{
    public static void main(String args[])
    {
        Shape1 s1 = new Shape1();        //编译错,Shape1 is abstract; cannot be instantiated
        s1.print();
    }
}


*/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -