简体   繁体   中英

java abstract class usage

Hi I am trying to execute this code in 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.? 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. change Shape to 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 .

So just change this name to ShapeNew.

 class Rect extends ShapeNew{

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM