IT박스

유형과 클래스의 차이점은 무엇입니까?

itboxs 2020. 6. 26. 19:07
반응형

유형과 클래스의 차이점은 무엇입니까?


클래스와 유형이 다른 점은 무엇입니까?

(일반적인 언어 불가지론 적 의미에서)


다음 답변은 Gof book ( Design Patterns )의 답변입니다.

객체의 클래스객체의 구현 방법을 정의합니다. 클래스는 객체의 내부 상태와 해당 작업의 구현을 정의합니다.

반대로, 객체 유형 은 해당 인터페이스 (응답 할 수있는 요청 집합) 만 참조합니다.

객체는 여러 유형을 가질 수 있으며 다른 클래스의 객체는 동일한 유형을 가질 수 있습니다.

//example in c++
template<typename T> 
const T & max(T const & a,T const &b)
{
return a>b?a:b;  //> operator of the type is used for comparison
}

max 함수에는 위의 요구 사항을 충족하는 모든 클래스를 사용하여 해당 클래스에 대한 특정 최대 함수를 생성하는 데 사용할 수있는 인터페이스 중 하나 인 > 자체 유형의 연산 이있는 유형이 필요합니다 .


나는 항상 '유형'을 '클래스'와 '프리미티브'의 포괄적 용어로 생각합니다.

int foo; // Type is int, class is nonexistent.

MyClass foo; // Type is MyClass, class is MyClass


Wikipedia에서 영감을 얻은 ...

에서 유형 이론 용어;

  • 유형은 추상적 인 인터페이스입니다.
    유형은 일반적으로 사람, 장소 또는 사물 또는 명 목화 된 것과 같은 명사를 나타냅니다.

  • 클래스 유형의 구현을 나타냅니다.
    구체적인 데이터 구조 및 서브 루틴 수집

    다른 구체적인 클래스는 동일한 추상 유형의 객체를 생성 할 수 있습니다 (유형 시스템에 따라 다름).

    * 예를 들어, 하나는 구현하는 유형을 Stack 두 가지로 클래스 : SmallStack(작은 스택에 대한 빠른하지만 제대로 저울)과 ScalableStack(물론 스케일하지만 작은 스택에 대한 높은 오버 헤드) *.

    마찬가지로, 주어진 클래스는 여러 다른 생성자를 가질 수 있습니다 .

여기에 이미지 설명을 입력하십시오

바나나 예.

  • Banana 유형은 일반적으로 바나나의 특성과 기능을 나타내는 것입니다.

  • ABCBananaXYZBanana 클래스는 생산 바나나의 방법을 나타내는 것입니다.
    (실제로 다른 바나나 공급 업체 또는 비디오 게임에서 바나나를 표현하고 그리는 다른 데이터 구조 및 기능)

    ABCBanana클래스는 다음이다 특히 바나나를 생산할 수있는 인스턴스ABCBanana 클래스를 , 그들은 것 오브젝트유형 바나나 .

프로그래머가 유형에 대해 단일 및 유일한 구현을 제공하는 것은 드문 일이 아닙니다. 이 경우 클래스 이름은 종종 type name 과 동일합니다 . 그러나 유형 (필요한 경우 인터페이스에서 추출 할 수 있음)과 클래스의 인스턴스 (객체)를 빌드하는 구현 (별도의 인터페이스를 구현할 수 있음)이 여전히 있습니다.


유형은 사용 가능한 모든 개체 템플릿 또는 개념에 대한 포괄적 인 용어입니다. 클래스는 그러한 객체 템플릿 중 하나입니다. 구조 유형, 정수 유형, 인터페이스 유형 등입니다. 이들은 모두 유형입니다.

원하는 경우 다음과 같이 볼 수 있습니다. 유형은 상위 개념입니다. 다른 모든 개념 : 클래스, 인터페이스, 구조, 정수 등은이 개념에서 상속됩니다.


유형에는 데이터에 대한 설명 (예 : 속성, 작업 등)이 포함됩니다.

클래스는 특정 유형 입니다. 개체의 인스턴스를 만드는 템플릿 입니다.

엄밀히 말하면 클래스는 특별한 개념으로, 객체의 일부 측면을 설명하는 메타 데이터의 하위 집합을 포함하는 패키지로 볼 수 있습니다 .

예를 들어 C #에서는 인터페이스와 클래스를 찾을 수 있습니다. 둘 다 유형이지만 인터페이스는 일부 계약 만 정의 할 수 있으며 클래스와 달리 인스턴스화 할 수 없습니다.

간단히 말해서 클래스객체의 속성과 동작을 캡슐화하는 데 사용되는 특수 유형 입니다.

Wikipedia는보다 완벽한 답변을 제공합니다.


가장 빠른 방법을 설명하려면 :

Struct는 유형이지만 Struct는 클래스가 아닙니다.

보시다시피, Type은 클래스의 정의뿐만 아니라 float, int, bool과 같은 구조체와 기본 데이터 형식을 나타내는 "추상적 인"용어입니다.


유형은 개념적으로 클래스의 상위 집합입니다. 넓은 의미에서 클래스는 한 가지 형식입니다.

클래스와 밀접한 관련이있는 인터페이스는 매우 추상적 인 클래스 인 매우 특수한 클래스로 볼 수 있습니다. 이것들도 유형입니다.

따라서 "유형"에는 클래스, 인터페이스 및 대부분의 언어 기본 형식이 포함됩니다. 또한 닷넷 CLR과 같은 플랫폼에도 구조 유형이 있습니다.


내 생각은 aku의 대답과 거의 일치합니다.

I see classes as a template for building objects, while types are a way to classify those objects, and provide us with an interface to them.

Python also adds metaclasses, that are just a mechanism to build classes, in the same way as classes build objects (and well, classes and metaclasses are both objects).

This response to the same question in lamba the ultimate seems to me like a perfect explanation.


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


To add another example of distinction: in C++ you have pointer and reference types which can refer to classes, but are not classes in and of themselves.

Bar b; // b is of type "class Bar"
Bar *b2 = &b; // b2 is of type "pointer to Class Bar"
Bar &b3 = b; // b3 is of type "reference to Class Bar"
Bar *b4[7]; // b4 is of type "7-element array of pointers to Class Bar"
Bar ***b5; //b5 is of type "pointer to a pointer to a pointer to Class Bar"

Note that only one class is involved, but a near infinite number of types can be used. In some languages, function are considered "first-class-objects" in which case, the type of a function is a class. In others, the type of a function is merely a pointer. Classes generally have the concepts of being able to hold data, as well as operations on that data.


I think of a type as being the set of things you can do with a particular value. For instance, if you have an integer value, you can add it to other integers (or perform other arithmetic operations), or pass it to functions which accept an integer argument. If you have an object value, you can call methods on it that are defined by its class.

Because a class defines what you can do with objects of that class, a class defines a type. A class is more than that though, since it also provides a description of how the methods are implemented (something not implied by the type) and how the fields of the object are laid out.

Note also that an object value can only have one class, but it may have multiple types, since every superclass provides a subset of the functionality available in the object's class.

So although objects and types are closely related, they are really not the same thing.


Type generally refers to the classification of primitive values - integers, strings, arrays, booleans, null, etc. Usually, you can't create any new types.

Class refers to the named set of properties and methods which an object is associated with when it is created. You can usually define as many new classes as you want, although some languages you have to create a new object and then attach methods to it.

This definition is mostly true, but some languages have attempted to combine types and classes in various ways, with various beneficial results.


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.


Interesting question. I think aku's answer is spot on. Take the java ArrayList class as an example

public class ArrayList<E> extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

An instance of the ArrayList class is said to be of type of every superclass it extends and every interface it implements. Therefore, an instance of the ArrayList class has a type ArrayList, RandomAccess, Cloneable, and so forth. In other words, values (or instances) belong to one or more types, classes define what these types are.


Different classes may describe the same type.

Type consists of these parts:

  1. Operations = syntax
  2. Description of operations = semantics

Class consists of these parts:

  1. Operations = syntax
  2. Implementation (= various implementations describe same semantics)

Some notes:

  • Interface (as in Java) is not type, because it does not describe semantics (describes only syntax)

  • Subclass is not subtype, because subclass may change semantics defined in superclass, subtype cannot change supertype semantics (see Liskov Substitution Principle, e.g. this LSP example).


Obviously, as there are languages with type system that are not OO programming languages, type must be a broader concept than class

Even in languages like Java, int is a (primitive) type, but not a class.

Hence: every class is a type, but not every type is a class.


If we think to this question in C# context, we reach bellow answer.

C# type system is divided into following categories:

Value types:

  • Simple types: like int, long, float, etc.
  • Enum types
  • Struct types
  • Nullable types

Reference types:

  • Class types
  • Interface types
  • Array types
  • Delegate types

As you can see there are many types in C# which Class is only one of them. There is just one important note: C#’s type system is unified such that a value of any type can be treated as an object. Every type in C# directly or indirectly derives from the object class type, and object is the ultimate base class of all types. Values of reference types are treated as objects simply by viewing the values as type object. Values of value types are treated as objects by performing boxing and unboxing operations.

so as I see, type is an umbrella over many items which class is one of them.

Referece: CSahrp Language Specification doc, page 4


In general language-agnostic sense - Class is an realization of the Type.

Often when this is the only realization of that type, you can use both terms to reference it in some context.

On the contrary, for example, in C# context - Class is just one of the many more implementations of a Type concept like primitives, structs, pointers etc.


This was a good question for me, which made me think hard. I would dare to say that Class is a compiletime thingy and Type is a runtime thingy. I say this because you write classes not types. The compiler then creates types from classes, and the runtime use types to create instances of objects.


Types in C, like Int Float, char etc define data that can be acted on with specific methods that can operate on them. It's no more complicated than that. Like for int I can add, subtract multiply and maybe divide. Those are my methods (or operations) for int. A Class is simply a definition of a new type. I first define what the data looks like. Maybe its a single bit. Maybe it's two words like a complex with a real and imaginary part. Or maybe its this complex thingy with 309734325 bytes representing the atomic makeup of a weird particle on Jupiter. I don't care. Just like an integer, I get to make up the operations I can do with this new data type. In the case of the integer I had add, subtract, etc. With this new data type I can define whatever operations I think make sense. They might be add subtract etc. but they may add other things. These are whatever methods I decide to add to my class.

The bottom line is that with a type in C, you have a definition of what the data is, ie; a byte, word, float, char etc. But any of these also implies what operations are legal and will produce reliable results.

A class is no different except it is up to you to define the interface and acceptable operations. The class defines these things and when you instantiate it in an Object it defines the behavior of the object just like a type definition defines the behavior of an integer when you operate on it.

Classes just give you the flexibility to define new types and everything about how they operate.

이것이 정의되면, "thingy"클래스의 객체를 인스턴스화 할 때마다, 내가 정의한 데이터 구조와 내가 할 수 있다고 말한 오퍼레이션 (메소드)을 갖습니다. "thingy"클래스는 C ++에서 정의 할 수있는 새로운 유형에 지나지 않습니다.

참고 URL : https://stackoverflow.com/questions/468145/what-is-the-difference-between-type-and-class

반응형