📄 graphics1.java
字号:
//【例3.8】 抽象类与抽象方法。
public abstract class Graphics1 //图形类,抽象类
{
private String shape; //形状
public Graphics1(String shape) //构造方法,不能是抽象方法
{
this.shape = shape;
}
public Graphics1()
{
this("未知");
}
public abstract double area(); //计算面积,抽象方法,分号";"必不可少
public void print() //显示面积,非抽象方法
{
System.out.println(this.shape+"面积为 "+this.area());
}
}
class Graphics1_ex
{
public static void main(String args[])
{
Graphics1 g1 = new Square1(10);//获得子类对象
g1.print(); //print()不是运行时多态性,area()是运行时多态性
Graphics1 g2 = new Circle1(10);
g2.print();
}
}
/*
程序运行结果如下:
正方形面积为 100.0
圆面积为 314.1592653589793
*/
/*
程序正确
1、抽象类也可以不包含抽象方法。例如,
public abstract class Shape //图形类,抽象类
{
public void finalize() //抽象类中可以有析构方法
{
}
public double area() //计算面积,非抽象方法,必须有方法体
{
return 0;
}
public void print()
{
}
}
程序错误
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 + -