【问题标题】:Using methods defined for an object type not working when I pass the same object type当我传递相同的对象类型时,使用为对象类型定义的方法不起作用
【发布时间】:2018-09-02 21:52:39
【问题描述】:

概述-
这是一个概念上的疑问。
我想实现一个数据结构来跟踪注册的手机。 所以我创建了三个类-
1) 有两个变量的节点类 -

class Node{
    public Object data;
    public Node next;
    public Node (Object datax) {
        this.data = datax;
    }
}


2) 手机类

class MobilePhone {
    public int phoneID;

    public MobilePhone(int number) {
        this.phoneID= number;
    }

    public int number() {
        return this.phoneID;
    }}<br>

3) 一个 Myset 类,它使用 Node 对象实现 LinkedList。
为了简单起见,我只是在这里展示了插入方法。

// the following method inserts a MobilePhone object in front of the Myset LL
public  void Insert(Object o) {

    if(IsMember(o)) {
        // print already a list
        return;
    }

    Node temp = head;

    head = new Node(o);

    head.next = temp;
    numberPhone++;
}

然后在我使用的另一个类中

MobilePhone m1MobilePhone = new MobilePhone(193);
set1Myset.Insert(m1MobilePhone);
System.out.println(set1Myset.head.data.number());

我只使用 Object 类对象定义了 Node 类和 Myset 以便概括。
但是,如果我传递 MobilePhone 类型的对象,我将无法使用 MobilePhone 类中定义的方法,因为编译器会不断显示诸如此类的错误 -
“方法 number() 未定义类型对象”。
我的问题是,如果我已经定义了我要传递的对象的数据类型,那么为什么我不能使用为该数据类型定义的方法呢​​? 我应该怎么做才能使用它们?

【问题讨论】:

  • 你需要使用泛型。
  • 您能详细说明一下吗?

标签: java object methods


【解决方案1】:

您指的是派生类的实例及其基类(对象类)的引用。在这种情况下,此引用只能用于访问 Object 类中定义的方法。

您的 Insert() 方法的签名必须允许 MobilePhone 类型的参数使用它的方法。

【讨论】:

  • 那么在insert方法中,不使用Object,如果我使用MobilePhone那么我可以使用MobilePhone的方法吗?
  • 在使用对象的时候有没有其他方法可以使用MobilePhone的方法,因为我想对不同的数据类型使用方法Insert?
  • 也许检查“泛型”可能会有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 2015-11-09
相关资源
最近更新 更多