Programmer dictionary: Class vs Type vs Object – Kotlin Academy
source link: https://blog.kotlin-academy.com/programmer-dictionary-class-vs-type-vs-object-e6d1f74d1e2e?gi=8af220c89c6f
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Programmer dictionary: Class vs Type vs Object
Class and type are often used interchangeably, while they have the different meaning. What are they? How they both relate to an object? In this article, we are going to explore differences and relations between all of them.
Object vs Class
The difference between object and class should be intuitive to most programmers:
Class is a blueprint or template from which objects are created.
Object is an instance of a class.
Here is a simple example:
class Aval a = A()
In above example A
is a class, but a
is pointing to an object. Class is what is defined using:
All objects are instances created using these templates. We can create multiple objects for a class defined using class
keyword, but for object declaration, object expression, and companion object there is a single object created.
Class vs Type
It was simple, but what about the difference between class and type?People are often asking: “Is String
a type or a class?”. The common answer is “Both because every class is a type”. It is not really true. We need to distinguish two different things:
- Classifiers, i.e. classes and interfaces
- Types
Classifiers generate a set of types. Let’s look at the example:
class Aval a = A()
We can say that in the above snippet we see definition of class A
, but the type of a
is A
. Therefore A
is both a name of the class and of the type. The class is a template for an object but concrete object have a type. Actually, every expression has a type! Here is a good simplification of class and type definitions:
A type summarizes the common features of a set of objects with the same characteristics. We may say that a type is an abstract interface that specifies how an object can be used.
A class represents an implementation of the type. It is a concrete data structure and collection of methods.
We’ve said that every classifier generates a set of types. In most cases, it generates a single type, but an example where a single class generates multiple types is a generic class:
class Box<T>
The Box
is a class, while Box<Int>
, Box<A>
, Box<List<String>>
are types generated by generic class Box
. Note that primitives and arrays in Java do not have a class or interface but they are types.
All this nomenclature comes from category theory which is highly adapted to theoretical computer science. If you need more, here is a great university article about the distinction between type and class.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK