[英]java abstract class usage
Hi I am trying to execute this code in Eclipse. 嗨,我正在尝试在Eclipse中执行此代码。
abstract class ShapeNew {
int length;
public abstract double area();
}
class Rect extends Shape{
Rect(int side){
this.length = side;
}
public double area(){
System.out.println("area of rectangle"+ length*length);
return length*length;
}
/**
* @param args
*/
public static class Area{
public static void main(String[] args) {
// TODO Auto-generated method stub
ShapeNew rect = new Rect(32);// I am unable to use this. The eclipse throws an error//
rect.area();
}
}
Can anyone help me with it. 谁能帮助我。 Why am I unable to assign a reference of ShapeNew to an object of Rect.?
为什么我无法将ShapeNew的引用分配给Rect。的对象? I get this error
我得到这个错误
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from Rect to ShapeNew
You have a typo: you need to extend from the class you've defined: 您有一个错字:您需要从定义的类中扩展:
class Rect extends ShapeNew {
(Also, it appears you've implemented a square rather than a rectangle given your area function squares a length). (同样,鉴于区域函数的长度为平方,看来您实现的是正方形而不是矩形)。
I think it's a simple typo. 我认为这是一个简单的错字。 Your abstract class name is ShapeNew on line 1 and you're trying to get a new instance of class Shape.
您的抽象类名称在第1行是ShapeNew,并且您正在尝试获取Shape的新实例。 change Shape to ShapeNew
将Shape更改为ShapeNew
You have to replace this line: 您必须替换此行:
class Rect extends Shape
By 通过
class Rect extends ShapeNew
abstract class ShapeNew {
int length;
public abstract double area();
}
class Rect extends ShapeNew{
Rect(int side){
this.length = side;
}
public double area(){
System.out.println("area of rectangle"+ length*length);
return length*length;
}
}
public class Area{
public static void main(String[] args) {
// TODO Auto-generated method stub
ShapeNew rect = new Rect(32);
rect.area();
}
}
You are getting an error because you abstarct class is : ShapeNew
and you inherit subclass from wrong name: Shape
. 您收到错误是因为您的绝对类是:
ShapeNew
并且您从错误的名称Shape
继承了子类。
So just change this name to ShapeNew. 因此,只需将此名称更改为ShapeNew。
class Rect extends ShapeNew{
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.