CSC/ECE 517 Fall 2007/wiki2 6 ap: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 293: Line 293:
==References==
==References==


Types and Classes [http://www.cs.cmu.edu/People/clamen/OODBMS/Manifesto/htManifesto/node6.html]<br>
[Types and Classes http://www.cs.cmu.edu/People/clamen/OODBMS/Manifesto/htManifesto/node6.html]<br>
Object Oriented Programming concepts on Wiki [http://en.wikipedia.org/wiki/Object-oriented_programming]<br>
[Object Oriented Programming concepts on Wiki http://en.wikipedia.org/wiki/Object-oriented_programming]<br>
OOP vs type classes [http://haskell.org/haskellwiki/OOP_vs_type_classes]<br>
[OOP vs type classes http://haskell.org/haskellwiki/OOP_vs_type_classes]<br>
Java Language Specification,Second Edition Chapter4: Types, Values, Variables [http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html]<br>
[Java Language Specification,Second Edition Chapter4: Types, Values, Variables http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html]<br>
Java Programming/Types on wiki [http://en.wikibooks.org/wiki/Java_Programming/Types]<br>
[Java Programming/Types on wiki http://en.wikibooks.org/wiki/Java_Programming/Types]<br>
Writing Classes in Ruby and Insipration for Example[http://rubylearning.com/satishtalim/writing_our_own_class_in_ruby.html]<br>
[Writing Classes in Ruby and Insipration for Example http://rubylearning.com/satishtalim/writing_our_own_class_in_ruby.html]<br>
What is the difference between class and type [http://www.velocityreviews.com/forums/t127376-what-is-the-difference-between-class-and-type.html]
[What is the difference between class and type http://www.velocityreviews.com/forums/t127376-what-is-the-difference-between-class-and-type.html]


==Further Reading / External Links==  
==Further Reading / External Links==  

Revision as of 21:26, 24 October 2007

Topic


Type vs. class. Survey the differences on type vs. class in object-oriented languages. Often, the distinction is that class pertains to an object, whereas type pertains to a variable. Consider the distinction between the two terms in several different programming languages. Cover the differences between type and class, from type-theoretic definitions to practical aspects.

Types vs Classes

In object oriented programming concepts, the difference between types and classes is not clearly understood. The differences between them are subtle and the two terms are often misunderstood to be the same. In the article we try to bring out the differences between Types and Classes and provide more insight into them. Furthermore, in OOP languages, classes are types, while most types are not classes. In pure object languages, by opposition (e.g. Smalltalk, Scala, perhaps Python), every type maps to a class.

Definition

Type

A type, in an object-oriented system, summarizes the common features of a set of objects with the same characteristics. It corresponds to the notion of an abstract data type. Type has 2 parts: the interface and the implementation(s). The interface, which is the only part visible to the user, consists of a list of operations and their signatures. The type implementation is of concern only to the type designer.

Class

A class, in object oriented systems, is a kind of metadata that describes the rules by which objects behave; these objects are referred to as instances of that class. A class specifies the structure of data (a.k.a. properties, fields, attributes, data members) within each instance as well as methods (functions) (a.k.a. behaviors) which manipulate the data of the object and perform tasks.

Types

Types are abstract views that define properties of a set of entities. Object-oriented programming languages must allow to implement these types. Consequently, once a type is implemented we have a particular representation of it available. We will use the seminal concept of the integer data type to explain the concept of type in detail. Programming languages such as C, Java, C++, Pascal and others already offer an implementation for it. Sometimes it is called int or integer. Once you've created a variable of this type you can use its provided operations. For example, you can add two integers:

  int i, j, k;    /* Define three integers */

  i = 1;          /* Assign 1 to integer i */
  j = 2;          /* Assign 2 to integer j */
  k = i + j;      /* Assign the sum of i and j to k */

The first line defines three instances i, j and k of type Integer. Consequently, for each instance the special operation constructor should be called. In our example, this is internally done by the compiler. The compiler reserves memory to hold the value of an integer and binds the corresponding name to it. If you refer to i you actually refer to this memory area which was constructed by the definition of i.

The implementation of types comprises of the data (internal structure of the object’s data) and operation (methods / procedures which implement the interface operations). By making users declare the types of variables at compile time, the system simplifies the procedure of checking the program correctness at compile time, thereby increasing programmer productivity. The types cannot be modified at run-time.

Properties of a Type

  • It exports a set of operations. This set is called interface.
  • Operations of the interface are the one and only access mechanism to the type's data structure.
  • Axioms and preconditions define the application domain of the type.


Classes

A class is a combination of state (data) and behavior (methods) that manipulate the state. A class is a blueprint for an object.It is an actual representation of a type. It therefore provides implementation details for the data structure used and operations specified in the type. Now we will define a class that implements the Integer data type:

  
class Integer {
  attributes: || implementation : 
    int i /* Integer data type */

  methods: || operation :
    setValue(int n) /* To assign value to i */
    Integer addValue(Integer j) /* To add integer j with i */
  }

In this notation class {...} denotes the definition of a class. Enclosed in the curly brackets are two sections attributes: and methods: which define the implementation of the data structure and operations of the corresponding class. Again we distinguish the two levels with different terms: At the implementation level we speak of attributes which are elements of the data structure at the class level. The same applies to methods which are the implementation of the class operations. In our example, the attribute is an ordinary integer of a programming language . We only define two methods setValue() and addValue() representing the two of the many operations that can be performed on an integer data type set and add, to make the comparison succinct and concise.

Although the specification of a class is pretty similar to that of a type, it is more of a runtime notion. There are two major aspects of a class – an object factory and an object warehouse. The object factory is the means by which objects of a class are created, using the new operation on the class. Object warehouse stores the set of objects that are instances of the class. Users can work with all these objects by performing all the allowed operations on them and thereby change the contents of the object warehouse. Thus, classes by no means determine the correctness of a program, rather they are used to create and manipulate objects, thereby making the system more flexible.

Types vs Classes

The concept of type itself is an abstraction, such as it can be either a value type or a reference type. In most languages, Type is the most general abstraction, with value types and reference types as subtypes of the general type.

Value types in turn can be of different kinds, such as the primitive types, but some languages also allow you to construct compound types which are classes. Reference types can also have different constructions, such as class as one and some would consider arrays as another.

In reality, type is whatever type you can assign as a type to a variable, which includes both value types and reference types. Since the concepts of types and classes are tightly coupled, in this article we don't explicitly show direct contrasts between them, but rather subtly bring out the differences in their implementations in various programming languages.

Types and Classes in C++

C++ supports three kinds of object types:

   * Fundamental types are built into the language (such as int, float, or double). Instances of these fundamental types are 
     often called variables.
   * Derived types are new types derived from built-in types.
   * Class types are new types created by combining existing types. These include Classes, Structures, and Unions.

Fundamental Types

Fundamental types in C++ are divided into three categories: integral, floating, and void. Integral types are capable of handling whole numbers. Floating types are capable of specifying values that may have fractional parts.The void type describes an empty set of values. No variable of type void can be specified — it is used primarily to declare functions that return no values or to declare generic pointers to untyped or arbitrarily typed data

Derived Types

Derived types are new types that can be used in a program, and can include directly derived types and composed derivative types.

Directly Derived Types

New types derived directly from existing types are types that point to, refer to, or (in the case of functions) transform type data to return a new type.

   * Arrays of Variables or Objects
   * Functions
   * Pointers of a Given Type
   * References to Objects
   * Constants
   * Pointers to Class Members

Composed Derivative Types

The following are the various composed derivative types:

   * Classes
   * Structures
   * Unions

Class types are derivatives of composed types. More on class types below.

Class Types

Class types are defined using the class, struct, and union keywords. For simplicity, types defined with these keywords are called class declarations. Class Type names are introduced as identifiers immediately after the compiler processes them (before entry into the class body); they can be used to declare class members. This allows declaration of self-referential data structures

Example :


#include <iostream.h>
#include <string.h>
#define TRUE = 1

class dog 
{
   //implementation
   public:
   dog()
   {
      legs = 4;
      bark = true;
   }

   void setDogSize(string dogSize)
   {
      _dogSize = dogSize;
   }
   string getDogSize()
   {
      return _dogSize;
   }
   void setBreed(string breed)
   {
      _breed = breed;
   }

   private: // attributes || fundamental types
   string _dogSize, _breed;
   int _legs;
   bool _bark;

};

int main()
{
   dog mongrel;//class types
   //setting specific attributes that makes it different from types
   mongrel.setDogSize("medium");
   mongrel.setBreed("country specific");
   cout << "Ricky is a " << mongrel.getDogSize() << " sized dog" << endl;
}

Output:

Ricky is a medium sized dog


Types and Classes in Java

Java is a strongly typed language i.e. the type of every variable and expression used in a program must be known at compile time. The type of a variable / expression defines the range of values that it can hold. The type of a variable also determines the operations that can be performed on that variable. The strong typing nature of Java enables it to determine errors at compile time.Whenever a variable is declared in Java, we need to mention its type, which may be a class, interface or a primitive. When an object of a subclass of some other class is instantiated, we can say that the object is of type subclass and type superclass and it can perform all operations of both the subclass and the superclass.

There are two different types in Java :

   * Primitive Types are boolean and numeric. The numeric types are the integral types byte, short, int, long, and char, and the         
     floating-point types float and double. 
   * Reference Types are class types, interface types and array types.


A side note on Null Types
There is also a special null type in Java, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.



Primitive Types

A primitive type is predefined by the Java programming language and named by its reserved keyword.Primitive values do not share state with other primitive values. A variable whose type is a primitive type always holds a primitive value of that same type. The value of a variable of primitive type can be changed only by assignment operations on that variable.

Reference Types

There are three kinds of reference types: class types, interface types, and array types.

 
ReferenceType:
	ClassOrInterfaceType
	ArrayType

ClassOrInterfaceType:
	ClassType
	InterfaceType

ClassType:
	TypeName

InterfaceType:
	TypeName

ArrayType:
        [ ]

Example :


import java.io.*;

class Dog 
{
   //implementation
   public Dog() //constructor
   {
      legs = 4;
      bark = true;
   }

   void setDogSize(String dogSize) //setter method
   {
      this.dogSize = dogSize;
   }
   String getDogSize() //getter method
   {
      return this.dogSize;
   }
   void setBreed(String breed)
   {
      this.breed = breed;
   }

   // attributes || fundamental types
   String dogSize = new String ("");
   Sting breed = new String ("");
   int legs;
   boolean bark;
   public static void main(String[] args)
   {
     Dog mongrel = new Dog();//class types
     //setting specific attributes that makes it different from types
     mongrel.setDogSize("medium");
     mongrel.setBreed("country specific");
     System.out.println("Ricky is a "+ mongrel.getSize() +" size dog");
  }
}

Output:

Ricky is a medium sized dog

Types and Classes in Ruby

Ruby being a dynamically typed, reflective object oriented language, every variable is an object and we do not explicitly mention their type as in other object oriented languages, rather the type is implicitly inferred from the type of the value which is assigned to them at runtime. Hence there is no distinction between primitive data types and object types in ruby. In Ruby, all classes are instances of the class Class. Whenever a new class is defined, an object of type Class is created and assigned to the Name of the class. Name.new is used to create a new object of the class. This invokes the new instance method in Class, which in turn calls the allocate method to allocate memory for the object, before finally calling the new object's initialize method. Thus, the construction of an object is separate from its initialization, and both can be over-ridden. The initialization is done via the initialize instance method while the construction is done via the new class method.

Example :

#since ruby is dynamic Oo language no explicit type assignment statements
class Dog 

   #implementation
   def initialize
      @legs = 4
      @bark = true
   end
   #attributes
   attr_accessor :dogSize, :breed 
end

#at runtime   
mongrel = Dog.new #dynamiclly typed
#setting specific attributes that makes it different from types
mongrel.dogSize = "medium" # string class type
mongrel.breed = "country specific" # string class type
puts "Ricky is a #{mongrel.dogSize} size dog"

Output:

Ricky is a medium sized dog

References

[Types and Classes http://www.cs.cmu.edu/People/clamen/OODBMS/Manifesto/htManifesto/node6.html]
[Object Oriented Programming concepts on Wiki http://en.wikipedia.org/wiki/Object-oriented_programming]
[OOP vs type classes http://haskell.org/haskellwiki/OOP_vs_type_classes]
[Java Language Specification,Second Edition Chapter4: Types, Values, Variables http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html]
[Java Programming/Types on wiki http://en.wikibooks.org/wiki/Java_Programming/Types]
[Writing Classes in Ruby and Insipration for Example http://rubylearning.com/satishtalim/writing_our_own_class_in_ruby.html]
[What is the difference between class and type http://www.velocityreviews.com/forums/t127376-what-is-the-difference-between-class-and-type.html]

Further Reading / External Links

Bjarne Stroustrup's article on OOP in C++ and beyond http://www.research.att.com/~bs/bs_faq.html#oop
B. Stroustrup, The C++ Programming Language, 3rd-ed., p. 158
Fundamentals of OOP and Data Structures in Java - Page xiii by Richard Wiener, Lewis J. Pinson
Type vs Class, A general overview http://lambda-the-ultimate.org/node/2079