简体   繁体   English

在这种情况下,为什么要在Java中使用接口?

[英]Why should I use interface in this situation in Java?

I'm trying to understand the basics of Java OOP concepts so I've a question about the interfaces as it confuses me a little. 我试图了解Java OOP概念的基础知识,所以我对接口有一个疑问,因为它使我有些困惑。 Below I was playing around with two classes. 下面我在上两节课。 One which implements the SizeComparable interface and the other which doesn't but works too. 一个实现了SizeComparable接口,另一个实现但不起作用。

public interface SizeComparable {
    int isHigher(SizeComparable obj);
}

public class Interesting implements SizeComparable {

    private int height;

    public Interesting(int height) {
        this.height = height;
    }

    public int getHeight() {
        return height;
    }

    public int isHigher(SizeComparable obj) {
        Interesting otherInteresting = (Interesting)obj;
        if(this.getHeight() > otherInteresting.getHeight()) {
            return 1;
        } else {
            return 0;
        }
    }

    public static void main(String[] args) {
        Interesting i1 = new Interesting(182);
        Interesting i2 = new Interesting(69);

        int result = i1.isHigher(i2);

        System.out.println("Is i1 higher than i2? Result: " + result);
    }

}

How is the code above better than the code bellow? 上面的代码比下面的代码好吗? Personally I don't understand because the code bellow those it's job great too. 就我个人而言,我不理解,因为代码也说明了它的出色表现。 Am I missing some concepts behind the interface idea? 我是否缺少界面概念背后的一些概念?

public class Interesting {

    private int height;

    public Interesting(int height) {
        this.height = height;
    }

    public int getHeight() {
        return height;
    }

    public int isHigher(Interesting obj) {
        if(this.getHeight() > obj.getHeight()) {
            return 1;
        } else {
            return 0;
        }
    }

    public static void main(String[] args) {
        Interesting i1 = new Interesting(182);
        Interesting i2 = new Interesting(69);

        int result = i1.isHigher(i2);

        System.out.println("Is i1 higher than i2? Result: " + result);
    }

}

I was trying to understand it ( here ), but I'm still unsure about this. 我试图( 在这里 )理解它,但是我仍然不确定。 Sorry if the question is a little silly, i just want to understand it completely. 抱歉,这个问题有点傻,我只想完全理解它。

If you have Interesting , Boring , Indifferent and Crazy classes which all represent some objects comparable by height, then all of them can implement the SizeComparable interface and thus be comparable to each other. 如果您有InterestingBoringIndifferentCrazy类,它们都表示某些对象在高度上可比,则它们都可以实现SizeComparable接口,因此彼此可比。

Without the interface you would need n methods in each class to compare it with itself and all the others. 没有接口,您将需要每个类中的n个方法将其与自身以及所有其他方法进行比较。

At the beginning it probably won't make much sense, however when you will start injecting dependencies, start testing or will write more than one implementation of interface, than it will really give you boost. 刚开始时,它可能没有多大意义,但是当您开始注入依赖关系,开始测试或编写不止一个接口实现时,它确实会给您带来很大的帮助。

Also it allows for multiple inheritance. 它还允许多重继承。 Sometimes you want thing like comparable - very generic interface that may be used by a lot of classes in your system. 有时您想要类似的东西-非常通用的接口,系统中的许多类都可以使用。 That will come with bigger systems and larger class hierarchies. 这将伴随更大的系统和更大的类层次结构。

Right now just trust rest of java world, and use them interfaces :) 现在,只需信任Java世界的其余部分,并使用它们的接口即可:)

and good luck 还有祝你好运

An interface is a contract that any class wishing to implement the interface agrees to follow. 接口是任何希望实现该接口的类都同意遵守的契约。 The reason for using an interface is to allow some other class or method to access the interface functions without requiring that the your class inherit from a common class... I'll modify your example to make it clearer: 使用接口的原因是允许其他一些类或方法访问该接口函数,而无需您的类继承自一个普通的类...我将修改您的示例以使其更清楚:

public interface HeightCapable {
    int getHeight();
}

public class Interesting implements HeightCapable {

    private int height;

    public Interesting(int height) {
        this.height = height;
    }

    public int getHeight() {
        return height;
    }

}

public class SomeOtherClass {
    public boolean isHigher(HeightCapable obj1, HeightCapable obj2) {
        // ... do something interesting
        if (obj1.getHeight() > obj2.getHeight()) {
            return true;
        }
}

In the example above, any class implementing the HeightCapable interface can call SomeOtherClass.isHigher() . 在上面的示例中,任何实现HeightCapable接口的类都可以调用SomeOtherClass.isHigher() Without the interface, any class wishing to call SomeOtherClass.isHigher() would need to inherit from a common class. 没有接口,任何希望调用SomeOtherClass.isHigher()的类都需要从一个通用类继承。 Java lacks multiple inheritance. Java缺乏多重继承。

If you want to have your SizeComparable objects comparable not to all other SizeComparable objects, but only to those of some type, you could use generic types. 如果要使您的SizeComparable对象与所有其他SizeComparable对象不具有可比性,而仅与某些类型的对象具有可比性,则可以使用通用类型。

interface SizeComparable<X> {

    /**
     * returns true if this object is higher than that object.
     */
    boolean isHigher(X that);

}

Then you could create your implementations like this: 然后,您可以这样创建实现:

public class Interesting implements SizeComparable<Interesting> {

    ...

    public boolean isHigher(Interesting obj) {
        return this.getHeight() > obj.getHeight();
    }

}

Or, you could even have another interface 或者,您甚至可以拥有另一个界面

public interface HeigthHaving extends SizeComparable<HeightHaving> {

    /**
     * returns the height of this object.
     */
    public int getHeigth(); 


    /**
     * compares this object's height with another objects height.
     * @return true if this.getHeight() > that.getHeight, else false.
     */
    public boolean isHigher(HeightHaving that);

}

Now every implementation of HeightHaving must implement the isHigher(HeightHaving) method (this would be the case even if we did not repeat it here), and should do that according to the specification here. 现在,HeightHaving的每个实现都必须实现isHigher(HeightHaving)方法(即使我们在此不重复,也是如此),并应根据此处的说明进行操作。 Other SizeComparable implementations are not affected of this, though. 但是,其他SizeComparable实现不受此影响。

The good thing here is that now for example sort algorithms can sort lists/arrays of any type X implementing SizeComparable, so you don't have to write it again for every new type of object you may want to sort by height. 这里的好处是,例如,排序算法现在可以对任何实现SizeComparable的X类型的列表/数组进行排序,因此您不必为可能要按高度排序的每种新型对象重新编写它。

(In fact, there is already a similar interface Comparable<X> in the standard API. Maybe you want to use this instead of your SizeComparable .) (实际上,标准API中已经有一个类似的接口Comparable<X> 。也许您想使用它而不是您的SizeComparable 。)

By the way, for a isXXX method usually a boolean return type is quite more sensible than an integer. 顺便说一句,对于isXXX方法,布尔返回类型通常比整数更明智。

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

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