CSC/ECE 517 Fall 2010/ch3 4b mt: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 110: Line 110:
Java is an object-oriented language, but it does make a clear distinction between the primitive type and Classes. int, float, char etc. are primitives, and the other data types other than the primitives are references. It is an interesting distinction to note, because of the differences in method calling system in different languages. Java makes a distinction in "calling-by-value" when a primitive is passed as a parameter, and "calling-by-reference" when an object is passed. This can be shown   
Java is an object-oriented language, but it does make a clear distinction between the primitive type and Classes. int, float, char etc. are primitives, and the other data types other than the primitives are references. It is an interesting distinction to note, because of the differences in method calling system in different languages. Java makes a distinction in "calling-by-value" when a primitive is passed as a parameter, and "calling-by-reference" when an object is passed. This can be shown   


Myth: "Objects are passed by reference, primitives are passed by value"
Some proponents of this then say, "Ah, except for immutable objects which are passed by value [etc]" which introduces loads of rules without really tackling how Java works. Fortunately the truth is much simpler:
Truth #1: Everything in Java is passed by value. Objects, however, are never passed at all.
That needs some explanation - after all, if we can't pass objects, how can we do any work? The answer is that we pass references to objects. That sounds like it's getting dangerously close to the myth, until you look at truth #2:
Truth #2: The values of variables are always primitives or references, never objects.
This is probably the single most important point in learning Java properly. It's amazing how far you can actually get without knowing it, in fact - but vast numbers of things suddenly make sense when you grasp it.
Why is all this important?
When we hear "pass by reference", we may understand different things by the words. There are some pretty specific definitions of what it should mean. If the Java model used pass-by-reference, then
<code><pre>
Object x = null;
giveMeAString (x);
System.out.println (x);
[...]
void giveMeAString (Object y)
{
    y = "This is a string";
}
</pre></code>
the result (if Java used pass-by-reference semantics) would be
This is a string
instead of the actual result:
null
Explaining the two truths above eliminates all of this confusion.
So what does passing a reference by value actually mean?
It means you can think of references how you think of primitives, to a large extent. For instance, the equivalent to the above bit of code using primitives would be:
<code><pre>
int x = 0;
giveMeATen (x);
System.out.println (x);
[...]
void giveMeATen (int y)
{
    y = 10;
}
</pre></code>
Now, the above doesn't print out "10". Why not? Because the value "0" was passed into the method giveMeTen, not the variable itself. Exactly the same is true of reference variables - the value of the reference is passed in, not the variable itself. It's the same kind of copying that happens on variable assignment. The first code snippet, if inlined, is equivalent to:
<code><pre>
// Before the method call
Object x = null;
// Start of method call - parameter copying
Object y = x;
// Body of method call
y = "This is a piece of string.";
// End of method call
System.out.println (x);
</pre></code> [4]


===C++===
===C++===
Line 139: Line 203:
     http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html
     http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html
[3] Ruby Reflection ,http://www.khelll.com/blog/ruby/ruby-reflection/
[3] Ruby Reflection ,http://www.khelll.com/blog/ruby/ruby-reflection/
[4] Java pass-by-value and pass-by-reference http://www.yoda.arachsys.com/java/passing.html

Revision as of 01:21, 21 October 2010

Types vs Classes


Relationship between Type and Class
Relationship between Type and Class

Introduction

It is often that we talk about types, strongly typed, weakly typed, classes. To make it clear, let us look into it clearly. Every programming language has a way to define a variable. A variable is a named address location which stores a particular value.


Types

Time for an analogy? Imagine a variable to be a vacant house. It could have animals, humans, robots, or another smaller house, or whatever you can think of. There has to be a way, from a third party perspective, so as to be cognizant of the kind of things that reside in the house. Types and typing is a concept which realizes this concept. A typed language or a strongly typed language is one where the type of a variable has to be declared so as to avoid any wrong dealings of the value during run time. For example, Java is a strongly typed language. If I need to use two integers for addition, I would explicitly have to mention them as an integer:-

  int integer1;
  int integer2;

However, we can’t then re-initialize it to any other type in its defined scope.

  integer1 = “Hello World”;  // cannot map an int to a String

In the case of non-typed languages, say Ruby, or Visual Basic, etc. We don’t need to specify a type.

  def variable1;
  def variable2;

Now, it could be initialized with anything,

variable1 = 3

as well as

variable1 = “Good morning Vietnam” are allowed. 


Classes

A class is a “type” of variable specification. The difference between a class and a regular primitive integer, character, etc is that a class:-

  1. consists of one or more primitive or non-primitive variables
  2. is a pre-defined structure
  3. defines methods which operate on the internal state of the object

The Type of Class is “Class”, just like the Type of integer is “integer” in case of strongly typed languages.

For example, in case of Java:-

“The types of the Java programming language are divided into two categories: primitive types and reference types. The primitive types are the boolean type and the numeric types. The numeric types are the integral types byte, short, int, long, and char, and the floating-point types float and double. The reference types are class types, interface types, and array types. There is also a special null type. An object is a dynamically created instance of a class type or a dynamically created array. The values of a reference type are references to objects. All objects, including arrays, support the methods of class Object . String literals are represented by String objects .” [2]

So, as mentioned before, in Java, there are two “Types”:-

  1. Primitive Type
  2. Reference Type

Classes, Interfaces, Arrays are all consolidations of Primitive types, so they just need to “point” to or reference the primitive ones, hence the name.

Types and Classes in Languages

Ruby

Ruby claims to be a strong object oriented language. It is object oriented to the extent that every thing is an object. Primitive datatypes are objects, and we can make use of the object oriented techniques on even the primitives. As mentioned before, Ruby is a dynamic typed language, as the type is bound at compile time. Everything in Ruby has a class. Every class in Ruby is inherited from class Class.

Type in Ruby is well defined as well. Using self inspection (reflection), we can find out whether a name is a Class, or a method. Let us see this in action:-

The first thing that comes to a one’s mind is something like :

5.class #=> Fixnum
"hello".class #=> String
  

But have you thought of your class as an object? Well that seems odd, but that’s how ruby works:

5.class #=> Fixnum
class Foo;end  #=> nil
Foo.class #=> Class

What does the above snippet of code mean exactly? It means 2 things : Foo is a constant and that constant holds(refers to) an object of Class type.

Let us prove that:

Foo = Class.new
(irb):8 warning: already initialized constant Foo
=> Foo

As you can see, we got a warning because we tried to initialize the constant Foo again.

So ,when you define some class ‘Foo’ in ruby, all you are doing is: 1-instantiating an object of type Class. 2-initializing a constant Foo that refers to that created object .

So, when we say “object” ,then we do mean any object; an object of Class type, or any object of any type.[3]

Java

As mentioned before, Java is a strongly typed language. The type of data needs to be declared before using. The types of "types" in Java are :

  * Primitive Types:-  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:- class types, interface types and array types. [2] 

Java is an object-oriented language, but it does make a clear distinction between the primitive type and Classes. int, float, char etc. are primitives, and the other data types other than the primitives are references. It is an interesting distinction to note, because of the differences in method calling system in different languages. Java makes a distinction in "calling-by-value" when a primitive is passed as a parameter, and "calling-by-reference" when an object is passed. This can be shown

Myth: "Objects are passed by reference, primitives are passed by value"

Some proponents of this then say, "Ah, except for immutable objects which are passed by value [etc]" which introduces loads of rules without really tackling how Java works. Fortunately the truth is much simpler:

Truth #1: Everything in Java is passed by value. Objects, however, are never passed at all.

That needs some explanation - after all, if we can't pass objects, how can we do any work? The answer is that we pass references to objects. That sounds like it's getting dangerously close to the myth, until you look at truth #2:

Truth #2: The values of variables are always primitives or references, never objects.

This is probably the single most important point in learning Java properly. It's amazing how far you can actually get without knowing it, in fact - but vast numbers of things suddenly make sense when you grasp it.

Why is all this important?

When we hear "pass by reference", we may understand different things by the words. There are some pretty specific definitions of what it should mean. If the Java model used pass-by-reference, then

Object x = null;
giveMeAString (x);
System.out.println (x);
[...]

void giveMeAString (Object y)
{
    y = "This is a string";
}

the result (if Java used pass-by-reference semantics) would be

This is a string

instead of the actual result: null

Explaining the two truths above eliminates all of this confusion.

So what does passing a reference by value actually mean?

It means you can think of references how you think of primitives, to a large extent. For instance, the equivalent to the above bit of code using primitives would be:

int x = 0;
giveMeATen (x);
System.out.println (x);
[...]

void giveMeATen (int y)
{
    y = 10;
}

Now, the above doesn't print out "10". Why not? Because the value "0" was passed into the method giveMeTen, not the variable itself. Exactly the same is true of reference variables - the value of the reference is passed in, not the variable itself. It's the same kind of copying that happens on variable assignment. The first code snippet, if inlined, is equivalent to:

// Before the method call
Object x = null;
// Start of method call - parameter copying
Object y = x;
// Body of method call
y = "This is a piece of string.";
// End of method call
System.out.println (x); 

[4]

C++

C

Note: purely procedural, however can be simulated by the concept of structs.

Perl

Python

Javascript

Discussion of Issues

Primitive Types

Advantages

Disadvantages

Class Types

Advantages

Disadvantages

References

[1] http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

[2] Java:- Types, Values and Variables

   http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html

[3] Ruby Reflection ,http://www.khelll.com/blog/ruby/ruby-reflection/ [4] Java pass-by-value and pass-by-reference http://www.yoda.arachsys.com/java/passing.html