java - 从另一个类的构造函数中获取值

标签 java constructor

我确信这对很多人来说都是一个非常简单的问题,但我正在努力解决这个问题。我试图从以下构造函数中获取一个值并将其放入 vector 中。

每次我将对象添加到 vector 中时,放置在 vector 内的值为空。如何将数字作为放入 vector 中的值?

CInteger 类:

public class CInteger  
{
    private int i;
    CInteger(int ii)
    {
        i = ii;
    }
}

在我的 A1 类中,构造函数和我获取值的尝试:

    Object enqueue(Object o) 
    {
        CInteger ci = new CInteger(88);
        Object d = ??
        add(tailIndex, d);// add the item at the tail
    }

感谢大家的见解和帮助,我仍在学习中。

编辑:已解决

CInteger 类:

public class CInteger implements Cloneable // Cloneable Integer 
{
    int i;
     CInteger(int ii)
    {
        this.i = ii;
    }

public int getValue()
    {
        return i;
    }

}

两种入队方法:

public void enqueue(CInteger i)  // enqueue() for the CInteger
{
    add(tailIndex, new Integer(i.getValue())); get int value and cast to Int object
}
public void enqueue(Date d)  // enqueue() for the Date object
{
    add(tailIndex, d);
}

非常感谢大家。 :D

最佳答案

您可以简单地重载队列类以获取日期和整数。无论哪种情况,听起来您都需要 CInteger 中的 getValue() 方法来访问 int 值。

public class CInteger
{
    //constructors, data

    public void getValue()
    {
        return i;
    }
}

然后你可以在另一个类中有两个 enqueue() 方法:

public void enqueue(Date d)
{
    add(tailIndex, d);
}

public void enqueue(CInteger i)
{
    add(tailIndex, new Integer(i.getValue()); //access the int value and cast to Integer object
}

Java会根据参数自动知道你调用的是哪一个。

关于java - 从另一个类的构造函数中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5373389/

相关文章:

java - 是否可以使用默认初始化过程在 EJB 模块中初始化 log4j?

Java:接收具有多个DatagramSockets的UDP datgram数据包

new Object([])/new Object(new Array()) 的 JavaScript 构造函数

c++ - 在 C++ 类构造函数中传递对象实例(无法编译)

java - JSP 导入类实现不解析类型

java - Oracle nvl 需要将 null 插入数字字段

java - GraphicsConfiguration 与 Canvas3D 不兼容

java - 如何在未初始化对象的构造函数中调用对象方法?

javascript - 在 JavaScript 中进行 Prototype 面向对象编程的最佳方法

c# - 从同一个类中的另一个构造函数调用构造函数