继承不起作用

时间:2014-08-27 14:25:12

标签: java

从我的代码中,我希望我的卧室课程能够继承超级课堂的长度和宽度。我在评论中填写了相应行中的错误。 我收到错误,我找不到出路。请帮帮我?

package index;

public class Room {
int length;
int breadth;

Room(int x,int y)
{
    length = x;
    breadth = y;
}
int area(){
    return (length*breadth);
}
}

class BedRoom extends Room{      //Implicit super constructor Room() is undefined for default constructor. Must define an explicit constructor
    int height;
    public void Bedroom(int x,int y,int z)
    {
        super(x,y);    //Constructor call must be the first statement in a constructor
        height=z;
    }


int volume(){
    return (length*breadth*height);
    }
}
class InherTest
{
    public static void main(String args[])
    {
        BedRoom room1 = new BedRoom(14,12,10); //The constructor BedRoom(int, int, int) is undefined
        int area1 = room1.area();
        int volume1 = room1.volume();
        System.out.println("Area1 = "+area1);
        System.out.println("Volume1 = "+volume1);
    }

}

4 个答案:

答案 0 :(得分:8)

在构造函数声明中,您只是拼错BedRoomBedroom。 (更正此问题将为您提供有关@HovercraftFullOfEels提及的问题的更简单易懂的错误消息:构造函数没有返回类型。)

答案 1 :(得分:4)

您的BedRoom类有 伪构造函数 ,而不是真正的构造函数。构造函数不会返回任何内容,也不会使任何内容无效。摆脱那个无效的陈述。

更改

public void Bedroom(int x,int y,int z)

public BedRoom(int x,int y,int z) // also capitalize correctly

答案 2 :(得分:2)

  • 构造函数的名称必须与类名匹配,但由于Java区分大小写Bedroom不是BedRoom类中构造函数的有效名称。
  • 构造函数也没有返回类型,因此请从中删除void

换句话说,替换

public void Bedroom(int x, int y, int z) {
//     ^^^^    ^ 

public BedRoom(int x, int y, int z) {

答案 3 :(得分:0)

更改为

 public void BedRoom(int x,int y,int z)

至于java卧室与BedRoom不同