繁体   English   中英

从同一个类中的方法调用构造函数

[英]Calling a constructor from method within the same class

我是java新手,我正在学习创建对象类。 我的一个家庭作业要求我在同一个对象类的方法中至少调用一次构造函数。 我收到一条错误,说明The method DoubleMatrix(double[][]) is undefined for the type DoubleMatrix

这是我的构造函数:

public DoubleMatrix(double[][] tempArray)
{
    // Declaration
    int flag = 0;
    int cnt;

    // Statement

    // check to see if doubArray isn't null and has more than 0 rows
    if(tempArray == null || tempArray.length < 0)
    {
        flag++;
    }

    // check to see if each row has the same length
    if(flag == 0)
    {
        for(cnt = 0; cnt <= tempArray.length - 1 || flag != 1; cnt++)
        {
            if(tempArray[cnt + 1].length != tempArray[0].length)
            {
                flag++;
            }
        }
    }
    else if(flag == 1)
    {
        makeDoubMatrix(1, 1);// call makeDoubMatrix method
    }

}// end constructor 2

这是我尝试调用构造函数的方法:

public double[][] addMatrix(double[][] tempDoub)
{
    // Declaration
    double[][] newMatrix;
    int rCnt, cCnt;

    //Statement

    // checking to see if both are of same dimension
    if(doubMatrix.length == tempDoub.length &&
            doubMatrix[0].length == tempDoub[0].length)
    {
        newMatrix = new double[doubMatrix.length][doubMatrix[0].length];

        // for loop to add matrix to a new one
        for(rCnt = 0; rCnt <= doubMatrix.length; rCnt++)
        {
            for(cCnt = 0; cCnt <= doubMatrix.length; cCnt++)
            {
                newMatrix[rCnt][cCnt] = doubMatrix[rCnt][cCnt] + tempDoub[rCnt][cCnt];
            }
        }
    }
    else
    {
        newMatrix = new double[0][0];
        DoubleMatrix(newMatrix)
    }

    return newMatrix;
}// end addMatrix method

有人能指出我正确的方向,并解释为什么我收到错误?

有人能指出我正确的方向,并解释为什么我收到错误?

原因是......你没有正确地声明你的对象。 由于答案很少,您需要提供一个名为new的关键字。 这个new关键字为堆内存中的DoubleMatrix类创建一个新对象。

else { newMatrix = new double[0][0]; new DoubleMatrix(newMatrix) }

希望这可以帮助

您可以使用this()另一个构造函数 (或super() 内部调用构造函数来调用父类构造函数),但是您不能使用另一个方法构造函数。 也许你打算创建一个新对象? 如果是这样,只需使用new Object(); 将为新对象调用构造函数。

您不能从方法调用构造函数,您只能使用此或超级关键字从其他构造函数调用构造函数。 您只能调用一次构造函数,它必须是构造函数体中的第一个语句。 如果不从contructore主体调用任何构造函数,java编译器将隐式地将super()语句插入构造函数中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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