【问题标题】:java call method from parent on object from implemented class来自父对象的java调用方法来自实现的类
【发布时间】:2015-11-18 12:17:26
【问题描述】:

我相信这很容易。我有一个名为vInteger 的java 类,它扩展了Integer 类(仅包含int 值、构造函数、getter)并实现了Comparing 类。那个有一个抽象方法compare(Comparing obj);,我在vInteger 类中实现了它。但是,我不能从Integer 类调用getter 来获取int 值。 这里有什么问题? :)

谢谢

【问题讨论】:

  • 实现类????
  • 你的类没有扩展java.lang.Integer,因为那个类被标记为final
  • 能出示相关代码吗?
  • “我不能调用 Integer 类的 getter 来获取 int 值” 为什么不呢? (请不要回答“因为我收到错误”,而是“因为我收到一个错误,上面写着 XYZ”。)

标签: java parent extends implements


【解决方案1】:

如果你看到 Integer 类,那么它是

public final class Integer  extends Number implements Comparable<Integer>

你不能扩展这个类,因为它是最终的

【讨论】:

    【解决方案2】:

    我假设您指的是自定义 Integer 类(不是一个好主意,顺便说一句,因为它会隐藏 java.lang.Integer,所以重命名它会更安全)。

    现在,您有一个看起来像这样的类(根据您的描述):

    public class vInteger extends Integer implements Comparing
    {
        ...
    
        public int compare(Comparing obj)
        {
            // here you can access this.getIntValue() (the getter of your Integer class)
            // however, obj.getIntValue() wouldn't work, since `obj` can be of any
            // class that implements `Comparing`. It doesn't have to be a sub-class of
            // your Integer class. In order to access the int value of `obj`, you must
            // first test if it's actually an Integer and if so, cast it to Integer
            if (obj instanceof Integer) {
                Integer oint = (Integer) obj;
                // now you can do something with oint.getIntValue()
            }
        }
    
        ...
    }
    

    P.S.,更好的解决方案是使用通用 Comparing 接口:

    public interface Comparing<T>
    {
        public int compare (T obj);
    }
    
    public class vInteger extends Integer implements Comparing<vInteger>
    {
        public int compare (vInteger obj)
        {
            // now you can access obj.getIntValue() without any casting
        }
    }
    

    【讨论】:

      【解决方案3】:

      我同意Mukesh Kumar

      你能试试下面的代码吗?

      public class VInteger extends Number implements Comparable<Integer> {
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-25
        • 1970-01-01
        • 2018-11-30
        • 1970-01-01
        • 2015-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多