CSC/ECE 517 Fall 2007/wiki2 6 mxz

From Expertiza_Wiki
Jump to navigation Jump to search

Assignment 2 - Topic 6

Type v.s. 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.


Type and Class

Types limit the values that a variable can hold or that an expression can produce, limit the operations supported on those values, and determine the meaning of the operations.[1] For example, a string type variable in c++ holds a string of characters.

        string str;
	str="I am string type";
	cout<<str.length();


A class is a construct used to group related fields and methods. It is the blueprint from which individual objects are created. It may be a combination of a type, a constructor and optionally a subtyping relation.[2] In following example, we define a class MyString inherited from String:

        class MyString < String
          def initialize
            ...
          end
          def method
            ...
          end
        end
        str = MyString.new


Type v.s. Class - Theoretic Differences

Generally speaking, type differs from class in the following ways:

  • The primary difference between type and class is that class pertains to an object, whereas type pertains to a variable.
  • Type is generally a compile-time concept which limits the values of a variable. The class of an object, though, exists and is important at runtime, and in the behavior of casting operations which provide the models to create the objects.
  • Classes have their own class methods and class variables which don't invoke any of its instances. For instance, we may have a Car Class which creates different kinds of cars. In this class we may have a variable counting the number of objects created. However, a type does not have such variables holding information of its instances.
  • 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. [3]


Type v.s. Class in Java

In Java, every variable and every expression has a type that can be determined at compile time. The type may be a primitive type or a reference type. The reference type includes class and interface.

Even though we say that class pertains to objects whereas type pertains to variable, in O-O languages like Java all classes are types and every object has a type. One of the difference between primitive types and classes are that classes have class variables that can hold information about its instances whereas primitive types don't have any way to hold information about its instances namely variables.

Note that sometimes a variable or expression is said to have a "run-time type". This refers to the class of the object at run time.[4]


Type v.s. Class in Ruby

In a purely object oriented programming language like Ruby, every variable is an object. Therefore, each type maps to a class and there is no distinction between primitive types and object types. In Ruby, you are able to superclass built-in types like strings and lists.

In Ruby, an objects type is not determined by which class it belongs to but by what it can do. That is why we can use duck typing Ruby. In Ruby an object is of a certain type if it behaves as that type. Class objects in Ruby are not explicitly declared to have a certain type. In Ruby the type of a variable depends upon what was last assigned to it. A variable can hold many different types during the lifetime of a script. [5]

Lets give an example to this. Lets say we define an increment method that takes an integer as a parameter. You will see in the below Java code that the input parameter will have an 'int' in front of it.

public void increment(int i){
   num += i;
}

In Ruby 'int' is not needed because a variable depends upon what was last assigned to it.

def increment(i)
   num += i;
end

Another difference is that Java uses inheritance as the mechanism for defining the type of an object. An object "is a" X if it implements X. While Ruby also supports inheritance, establishing "is a" relationships is not its main purpose.

Type v.s. Class in Python

Python is an important example. In earlier versions of Python derived types were not created from built in types but just from user defined classes. After Python 2.2 this has changed and "type/class unification" is accomplished. That is like Ruby, every type started mapping on a single class. Python intended to remove most of the differences between built-in types and user-defined classes. Perhaps the most obvious one is the restriction against using built-in types (such as the type of lists and dictionaries) as a base class in a class statement. In the old version class and type used to not be the same thing. All instances of old-style classes are of type 'instance' which is a type defined in Python (InstanceType). New-style classes elevate Python-level classes to types equal to the built-in ones, which is why the word "type" is now sufficient for both type and class. [6]


Even though Python has made changes there are still differences with Ruby which is also a dynamically typed language. Emulating container types (like arrays and hashes) in Python is harder because there are different methods you have to use for "Emulating callable Objects", "Emulating numeric types", "Emulating sequences" etc.. In Ruby, you just derive from the respective base classes (or extend them directly). Namely if you want to extend a numeric container type like float arrays you just extend 'float'. So, Ruby's type system is much simpler and cleaner and allows a smaller and simpler language core.


Types v.s. Class in C++

C++ like Java has different kinds of types. Types can be built in, user defined or derived from preexisting classes. Built in types are types that are already defined in the language like int or String. User defined types are types created from user written classes. Lastly derived types are types created form extending the other two types of classes. "derived class" in C++ is "subclass" in Java. When a class extends a base class, to derive a new class with all the base's variables and methods, plus some of its own, we call the new class the subclass, and the base class the new class's "superclass". [7]


In C++ like Java every variable has a type at compile time and the variable needs to be type casted if the type of the variable needs to be change.


Practical Differences

An example in Java

Let's look at an example about types-subtypes and classes-subsclasses

public interface Colorable {
	void setColor(byte r, byte g, byte b);
}
class Point { int x, y; }
class ColoredPoint extends Point implements Colorable {
	byte r, g, b;
	public void setColor(byte rv, byte gv, byte bv) {
		r = rv; g = gv; b = bv;
	}
}
class Test {
	public static void main(String[] args) {
		Point p = new Point();
		ColoredPoint cp = new ColoredPoint();
		p = cp;
		Colorable c = cp;
	}
}

In the code above,

  • The variable p of class Test has type Point and is initially assigned a reference to a new instance of class Point.
  • The variable cp similarly has as its type ColoredPoint, and is initially assigned a reference to a new instance of class ColoredPoint.
  • The assignment of the value of cp to the variable p causes p to hold a reference to a ColoredPoint object. This is permitted because ColoredPoint is a subclass of Point, so the class ColoredPoint is assignment compatible with the type Point.
  • The variable c has as its type the interface type Colorable, so it can hold a reference to any object whose class implements Colorable; specifically, it can hold a reference to a ColoredPoint.

Note that even though a variable or an expression can have an interface type, instances of interfaces cannot be created. So an expression such as "new Colorable()" is not valid. [8]


Syntax Differences

Here is how we define a class in java. Defining classes in different O-O languages are not so different:

class Car
{
       int numOfWheels = 4;

       void changeWheelNum(int newValue) 
       {
            numOfWheels = newValue;
       }
}

And below you can see how we define it in Ruby. There is only some syntax difference.

class Car
       numOfWheels = 4

       def changeWheelNum(newValue) 
       
            numOfWheels = newValue
       end
end

The class Car that we defined in the above code is from now on a Type. But a user cannot define a primitive type which does not stick to a class. Lets say we are going to give a name to our car. Instances of built in types can be created as :

String carName= "Type defined";

While in Java you have to define the type every time you create a new variable, in Ruby this is not needed as stated above. In Ruby we don't need type String be written. This is because in Ruby types are defined as how they behave.

carName= 'No Type'

When you want to change the type of an object in Java you need to type cast it, in Ruby this is not needed. We saw how instances of built in types could be called for Java and Ruby. To create an instance of a type derived classes we need to use the 'new' keyword. In order to it in Java you can type the following:

Car mycar = new Car();

It's similar in Ruby we just don't need the 'Car' type definition at the beginning.


Types can also be created from inheritance.

class SportsCar extends Car 
{
     int capacity = 2;
}

Now we have a Car type defined and also a SporsCar that is a subtype of Car. There is a special relationship between the type of a subclass and the type of a superclass, in that a subclass of a class defines a subtype of the superclass’ type.


Conclusion

As a summary, a type is a set of data, values and the operations performed on them. Types can be created in different ways which include primitive types, class types and subtypes (by inheritance or interface).


Classes model abstract concepts that play an important role in the system with well-defined responsibilities and relations with other classes. And in o-o programming languages, every class defines a type. When you create an instance of a class you create an object and when you create an instance of a variable you create a variable.


The type of every variable is known at compile time. However, you do not need to define the type of a variable explicitly in Ruby, because Ruby uses Unbounded Polymorphism. In languages like Ruby and later versions of Python every type maps to a class. In other words there are no primitive types and every type is defined through a class.

References

[1] Sun website on types

[2] http://lambda-the-ultimate.org/node/2079

[3] http://c2.com/cgi/wiki?PythonVsRuby

[4] Discussion in a blog

[5] http://www.cs.mun.ca/~donald/slug/2003-10-16/

[6] http://alek.xspaces.org/2005/02/27/ruby-type-explosion

[7] http://mindprod.com/jgloss/derivedclass.html

[8] Ruby Learning

[9] http://www.cs.cmu.edu/People/clamen/OODBMS/Manifesto/htManifesto/node6.html

[10] http://www.nabble.com/class-vs-type-t4652989.html

[11] An Introduction to Object-Oriented Design and Design Patterns Using Java by Dale Skrien

[12] http://www.daniweb.com/forums/post9552.html

[13] Wikipedia

[14] http://ootips.org/classes-vs-builtins.html

[15] http://www.velocityreviews.com/forums/t283031-return-by-value-primitive-type-vs-class-type.html