简体   繁体   English

object 的类型,同时实例化实现接口的 class

[英]Type of object while instantiating a class that implements interface

Let's say I have a class named TestClass that implements interface named TestInterface.假设我有一个名为 TestClass 的 class 实现名为 TestInterface 的接口。 What is the difference in creating following objects:创建以下对象有什么区别:

TestInterface test1 = new TestClass();
TestClass test2 = new TestClass();

If there is no differences, which one is the better convention?如果没有差异,哪一个是更好的约定?

interface TestInterface {
    public void function2();
}

public class TestClass implements TestInterface {
    public static void main(String... args) {
        TestInterface testInterface = new TestClass();
        TestClass testClass = new TestClass();

        /* function1 belongs to TestClass class only */
        testInterface.function1(); // This gives you compile time error as function1 doesn't belong to TestInterface
        testClass.function1(); // Whereas this is ok.

        /* function2 belongs to TestInterface and TestClass, so function2 can be called from both object (testClass and testInterface) */
        testInterface.function2(); 
        testClass.function2();
    }
    public void function1() {
        System.out.println("This is function 1");
    }
    public void function2() {
        System.out.println("This is function 2");
    }
}

暂无
暂无

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

相关问题 Java 实例化实现接口的泛型类型 - Java instantiating a generic type which implements an interface 如果一个类实现了一个接口,并且被分配给一个具有该接口类型的变量,那么该对象是什么类型的? - If an class implements an interface, and is assigned to a variable with a type of that interface, what type is that object? 使用接口类型实例化实现接口的类对象 - Using a interface type to instantiate a class object that implements the interface 从接口对象转换为实现它的类的对象? - Casting from an interface object to an object of a class that implements it? 如何在该接口类型的对象上调用实现接口的类中的方法? - How can I call a method which is in a class which implements an Interface, on an object of that interface's type? 如何使用来自实现父接口的 class 的构造函数初始化接口类型的 object? - How can I initialize an object of type interface with a constructor from a class that implements the parent interface? 如何声明接口类型的变量,然后将实现接口的 Class 的 object 分配给该变量,以及如何测试? - How to declare a variable of type Interface and then assign to the variable an object of a Class that implements the Interface, and how to test this? 实现接口的类的类型是什么 - What is the type of a class which implements a interface 如何检查类类型并查看其是否实现了接口 - How to check for a class type and see if it implements an interface 为实现接口的类强制执行返回类型 - Enforcing return type for an class that implements an interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM