Java构造函数,非法表达

时间:2015-03-12 12:32:19

标签: java

所以我在这个构造函数中得到Illegal start of expression错误:

public V10String()
{
  this.left = left;
  this.val=val;
  this.right=right;
  this.height=height;
}
当我删除public时,

似乎消失了。但是,leftright等无法识别。这就像我的教授AFAIK一样。它有什么问题?

2 个答案:

答案 0 :(得分:2)

成员应该在构造函数之外声明:

public class V10String
{
    public int height;
    public String val;
    public AVLTreeNode left,right;

    public V10String() // this constructor assign default values to the members
    {
        this.height = 0;
        this.val    = null;
        this.left   = null;
        this.right  = null;    
    }

    // this constructor assigns to the members values passed to it by the caller
    public V10String(int height, String val, AVLTreeNode left, AVLTreeNode right) 
    {
        this.height = height;
        this.val    = val;
        this.left   = left;
        this.right  = right;
    }
}

在构造函数(或任何其他方法)中声明的变量是局部变量,并且没有访问修饰符(因为它们只能由声明它们的方法/构造函数访问)。

答案 1 :(得分:2)

Eran的答案是对的,但我想你想做点什么,

您还需要在构造函数中传递参数。

public int height;
public String val;
public AVLTreeNode left,right;

public V10String(int height, String val, AVLTreeNode left, AVLTreeNode right)
{
    this.height = height;
    this.val =  val;
    this.left =  left;
    this.right = right;
}