即使没有arg构造函数,隐式超级构造函数也是未定义的?

时间:2014-05-20 04:36:28

标签: java inheritance constructor

所以我是Java的新手,我得到了这个错误,说构造函数是未定义的。我做了一些研究,发现我需要添加一个无参数构造函数,但是即使我这样做了,我仍然会得到错误。

import javax.swing.JComponent;


public abstract class Block extends JComponent{
    Block(){}
}

这是我还没有完成任何内容的超级课程

import java.awt.*;
import java.util.Arrays;
import javax.swing.*;

public class Head extends Block{
    private int xpos;
    private int ypos;
    private boolean[] m;

    public Head(){
        xpos = getWidth()/2;
        ypos = getHeight()/2;
    }
}

这是给出错误的子类:/

2 个答案:

答案 0 :(得分:1)

你的无参数构造函数有默认修饰符 - 除非HeadBlock在同一个包中,Head无法访问它。您应该将其定义为public

public abstract class Block extends JComponent{
    public Block(){}
}

......或者至少受到保护:

public abstract class Block extends JComponent{
    protected Block(){}
}

......或者,根本不是。这将导致Java隐式创建一个具有public访问权限的无参数空构造函数:

public abstract class Block extends JComponent{
}

答案 1 :(得分:1)

你的抽象类中不应该有参数构造函数是不必要的......你可以有一个参数化的构造函数但是你必须在你的子类的第一行调用super()。例子......

import javax.swing.JComponent;


public abstract class Block extends JComponent{
    int height, width; // just for example only you can have anything you want
    Block(int h, int w){  //you can have anything as per you requirement
        height=h; width=w;
    }
}

&安培;这是儿童班......

import java.awt.*;
import java.util.Arrays;
import javax.swing.*;

public class Head extends Block{
    private int xpos;
    private int ypos;
    private boolean[] m;

    public Head(int h, int w){
        super(h, w);  //note this step...you have to call the constructor of super class by using super(..); and remember to pass parameter..
        xpos = getWidth()/2;
        ypos = getHeight()/2;
    }
}

如果你只是默认没有参数构造函数......你只需用super(h, w);替换super(); ......认为它会对你有所帮助..