本文介绍了Java:帮助理解接口作为数据类型的用途?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解有关Java教程这一部分的一些代码片段:

I am having trouble understanding with some of the code snippets about this part of the Java tutorial: http://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html

public Object findLargest(Object object1, Object object2) {
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   if ((obj1).isLargerThan(obj2) > 0)
      return object1;
   else 
      return object2;
}

和:

public interface Relatable {

    // this (object calling isLargerThan)
    // and other must be instances of 
    // the same class returns 1, 0, -1 
    // if this is greater than, 
    // equal to, or less than other
    public int isLargerThan(Relatable other);
}




  1. 在第一个例子中,为什么我要向下转发对象类型为Relatable类型?如果第一个方法不包含前两个语句会发生什么?

  2. 假设我写了一个实现Relatable接口并具有findLargest方法的Rectangle类。如果我知道我正在比较两个Rectangle对象,为什么不让第一个方法将对象向下转换为Rectangles呢?


推荐答案


  1. 您将 Objects 转换为 Relatable types,因为否则您无法使用 Relatable 接口中声明的方法。由于 Object 没有 isLargerThan 方法,你会在没有强制转换的情况下得到编译器错误

    老实说,在我看来,这里显示的 findLargest 方法设计得不是很好;更好地说明Interfaces的目的是要求 Relatable 对象作为参数,如下所示:

  1. You cast the Objects into Relatable types because otherwise you cannot use the methods declared in the Relatable interface. Since Object does not have the isLargerThan method, you would get a compiler error without casting.

    Honestly, in my opinion the findLargest method as shown here was not very well designed; a better illustration of the purpose of Interfaces would be to ask for Relatable objects as the parameters like so:

public Object findLargest(Relatable object1,Relatable object2){
//实现未显示以节省空间
}



这样,用户必须传递 Relatable 对象,但是他们可以传递任何类实现 Relatable 的对象(例如矩形

public Object findLargest(Relatable object1, Relatable object2) { //implementation not shown to save space}

This way, the user must pass Relatable objects, but they can pass any object whose class implements Relatable (such as Rectangle)

如果我知道我正在比较两个Rectangle对象......

是的,如果你知道你正在比较两个Rectangle对象,那么接口的用处很少,但是接口的目的是允许你创建一个可以使用的通用类型对象定义几个不同类的共同特征

例如,如果你还有一个 Circle 类和一个 Square class(两者都实现了 Relatable )?在这种情况下,您不一定知道完全类型的对象,但您会知道它是 Relatable ,所以最好转换为 Relatable 并在这种情况下使用 isLargerThan 方法。

"If I know that I'm comparing two Rectangle objects..."

True, if you know that you are comparing two Rectangle objects, there is little use for an interface, but the purpose of interfaces is to allow you to create a generic "type" of object that can be used to define common features of several different classes.

For example, what if you also had a Circle class and a Square class (both of which implemented Relatable)? In this case, you do not necessarily know the exact type of object you have, but you would know that it is Relatable, so it would be best to cast to type Relatable and use the isLargerThan method in a case like this.

这篇关于Java:帮助理解接口作为数据类型的用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 00:14