What is the difference between Type and Class?

前端 未结 20 2307
梦谈多话
梦谈多话 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

提交回复
热议问题