由于Super Class对象不能在主函数中实例化,因此在类名之前指定了abstract关键字。但是在SuperClass重写方法之前使用abstract关键字与不使用有什么区别呢?有人可以解释一下吗?
以下是示例,请查看评论部分。
abstract class Figure
{
int dim1;
int dim2;
Figure()
{
dim1=-1;
dim2=-1;
}
Figure(int p,int q)
{
dim1=p;
dim2=q;
}
abstract void Area() //This line is working without abstract for me.
{
System.out.println("The area is undefined.");
}
}
class Rectangle extends Figure
{
int vol;
Rectangle()
{
super();
}
Rectangle(int p,int q)
{
super(p,q);
}
void Area()
{
vol=dim1*dim2;
System.out.println("The area of the rectangle is: "+vol);
}
}
class Triangle extends Figure
{
int vol;
Triangle()
{
super();
}
Triangle(int p,int q)
{
super(p,q);
}
void Area()
{
vol=dim1*dim2/2;
System.out.println("The area of the rectangle is: "+vol);
}
}
public class Area
{
public static void main(String[] args)
{
Rectangle r=new Rectangle(10,20);
Triangle t=new Triangle(6,10);
Figure fref;
fref=r;
r.Area();
fref=t;
t.Area();
}
}
最佳答案
使用 abstract
修饰符,这是无效代码 - 您无法在声明抽象方法时指定它的主体。它应该只是:
abstract void Area();
(这不包括违反命名约定等)
抽象方法的重点是强制子类提供实际的实现,通常是因为抽象类本身不知道如何提供。如果您可以在抽象类中提供实现,请考虑将其设为普通方法,如果子类愿意,可以覆盖该方法。
请注意,可能有一个没有抽象方法的抽象类,但这种情况相对不常见。
参见section 8.4.3.1 of the Java Language Specification和 "abstract" part of the Java tutorial了解更多信息。
关于java - 方法重写中父类(super class)方法之前的抽象关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9178748/