What is the difference between Type and Class?

前端 未结 20 2220
梦谈多话
梦谈多话 2020-11-28 01:00

What makes a type different from class and vice versa?

(In the general language-agnostic sense)

相关标签:
20条回答
  • 2020-11-28 01:35

    Taken from the GoF citation from below:

    An objects's class defines how the object is implemented .The class defines the object's internal state and the implementation of its operations.

    In contrast, an objects's type only refers to its interface -the set of requests to which it can respond.

    I want to provide an example using Java:

    public interface IType {
    }
    
    public class A implements IType {
    public A{};
    }
    
    public class B implements IType {
    public B{};
    }
    

    Both classes A and B implement the interface and thus are of the type IType. Additionally in Java, both classes produce their own type (respectively to their class name). Thus the class A is of type A and IType and the class B is of type B and IType satisfying:

    An object can have many types, and objects of different classes can have the same type.

    The difference between subtypes and subclass probably helps to understand that issue as well:

    https://www.cs.princeton.edu/courses/archive/fall98/cs441/mainus/node12.html

    0 讨论(0)
  • 2020-11-28 01:35

    Types and classes are related but not identical. My take is that classes are used for implementation inheritance, whereas types are used for runtime substitution.

    Here is a link explaining the substitution principle and why subclasses and subtypes are not always the same thing (in Java for example). The wikipedia page on covariance and contravariance has more information on this distinction.

    0 讨论(0)
提交回复
热议问题