Java覆盖问题

时间:2014-12-19 14:18:25

标签: java

我的类Shape由类Rectangle继承,如下所示:

//Class Shape
public class Shape {
    public double area(){
        return 0.0;
    }
}

//Class  Rectangle 
public class Rectangle extends Shape{

    private int width;
    private int height;
    public Rectangle(int width,int height){
        this.width=width;
        this.height=height;
    }

    public void helloRectange(){
        System.out.println("Hello Rectangle");
    }


    public double area(){
        return this.height*this.width;
    }

}

//And Test Class


public class TestShape {

    public static void main(String []arge){

        Shape shape2=new Rectangle(10,20);

        shape2.helloRectange();


        System.out.println("Rectange is"+shape2.area());
    }

}

我无法使用shape2.helloRectange();对象调用shape2方法?有人可以详细解释。

错误是:

  

线程中的异常" main" java.lang.Error:未解决的编译问题:方法helloRectange()未定义为com.test.overriding.concept.TestShape.main(TestShape.java:9)上的Shape类型

5 个答案:

答案 0 :(得分:4)

由于Shape类没有方法helloRectange,因此请更改:

Shape shape2=new Rectangle(10,20);

到:

Rectangle shape2=new Rectangle(10,20);

或投射对象,如:

((Rectangle)shape2).helloRectange();

答案 1 :(得分:2)

对于正确的多态性,你应该声明Shape abstract并为其添加一个hello方法。

然后,在Rectangle中,使用相同的参数创建一个hello方法。

它看起来像这样:

//Class Shape
public abstract class Shape {
    public abstract void hello();
    public double area(){
        return 0.0;
    }
}

//Class  Rectangle 
public class Rectangle extends Shape{

    private int width;
    private int height;
    public Rectangle(int width,int height){
        this.width=width;
        this.height=height;
    }

    @Override
    public void hello(){
        System.out.println("Hello Rectangle");
    }


    public double area(){
        return this.height*this.width;
    }

}

然后这将起作用

//And Test Class


public class TestShape {

    public static void main(String []arge){

        Shape shape2=new Rectangle(10,20);

        shape2.hello();


        System.out.println("Rectange is"+shape2.area());
    }

}

请注意,Java中的所有方法都是virtual。对于所有语言都不是这样,在C#这样的事情中你可能必须指定虚拟关键字(abstract可能会自动暗示virtual,但是)

答案 2 :(得分:1)

因为它是Shape对象,并且形状没有helloRectange函数。尝试将其设为矩形:

Rectangle shape2 = new Rectangle(10,20);
shape2.helloRectange();

答案 3 :(得分:0)

    Shape shape2=new Rectangle(10,20);

该行单独表示执行Rectangle类的Shape类方法的实现。由于Shape没有方法helloRectangle,因此无法访问它。

答案 4 :(得分:0)

你不能这样做是因为你使用了多态分配和对象的静态类型Shape。即使动态类型为Rectangle并且对象本身也有方法,但如果没有强制转换,则无法调用它:

((Rectangle)shape2).helloRectangle();

这是因为编译器不知道对象的动态类型,因此不知道该方法存在于那里。

阅读有关静态/动态多态性的更多信息:

http://www.oracle.com/technetwork/java/neutral-137988.html

http://beginnersbook.com/2013/04/runtime-compile-time-polymorphism/