1.3. Object-Oriented Programming Review: C++ vs. Java

Time: 00:06:08 | Download: Large, Large (CC), Small | Streaming, Streaming (CC)| Slides (PDF)

Although our initial study of C++ focuses on the procedural programming paradigm, we will nevertheless utilize some object-oriented C++ features. Even though there are a few syntactic differences between Java and C++, your experience with Java in CS 1400 should be sufficient to carry you through the first few chapters. The following table reviews some concepts and terminology as used in the text or as you might see in other places.

Term or Concept Object-Oriented ParadigmJavaC++
Supported Paradigm Object-Oriented Object-Oriented Object-Oriented
Procedural
class class class class
object object, instance object, instance object, instance
Create an object from a class instantiate instantiate instantiate
Data not associated with a class N/A N/A variable
Operation not associated with a class N/A N/A function
Data associated with or stored in a class attribute instance variable,
instance field
data member,
member variable
Operation associated with a class behavior, operation method member function
Object-Oriented Paradigm: Concepts and Terms. At the conceptual level, object orientation is language-independent (sometimes called language agnostic). However, the object-oriented paradigm and various object-oriented programming languages often use different terms to name the same concept. The table compares the concept names common in pure object orientation with the terms used in C++ and Java. (Note that C++ is a hybrid language supporting both the object-orientated and the older procedural programming paradigms.)

Class vs. Object

From its name, it seems like object-oriented programming is all about objects. Yet, when we write an object-oriented program, our code defines a feature called a "class" and both C++ and Java include class as a keyword - but neither has object as a keyword. We previously used a cookie-cutter and cookies metaphor to illustrate the relationship between a class and the objects instantiated from it.

In the cookie-cutter metaphor, the cutter plays the role of the class while the cookies are the objects. A cookie-cutter describes the shape and the size of a cookie, but it's inedible and does not consist of any cookie ingredients. Alternatively, we make cookies from flour, sugar, and butter. Once we make the cookie dough, we can stamp out as many cookies as wanted with the cookie cutter. Classes and objects are fundamentally connected, so at times the terms are used interchangeably. Nevertheless, the two concepts are distinct.

So, we can say that a class is a description that describes three characteristics of the objects that are created or instantiated from it:

  1. The name of the class becomes a new data type that may be used throughout the program and is the type of objects instantiated from it.
  2. Each class forms an aggregate data type, which means that it can hold many, smaller variables. The class specifies the names and types of all the variables in the objects instantiated from the class.
  3. Classes also contain functions or methods that can operate on the data or variables stored in the object. The class specifies the name of each function, its return type, and the number and type of each argument.

Just as cookies have ingredients, so do objects. Memory is the "raw ingredient" programmers use to make objects. One of the most striking differences between C++ and Java is where and how programmers allocate that memory. The following figures illustrate the differences, which we revisit in detail in chapter 4.

C++ and Java Syntax

The object-oriented paradigm requires three main characteristics: encapsulation, inheritance, and polymorphism. The latter two characteristics are discussed later in the semester. We achieve encapsulation by packaging data and the operations that use that data together into an entity called an object. Java and C++ use different terms to name class variables and operations. Java calls them instance variables or fields and methods, respectively, which denotes that they "belong" to instances or objects. C++ calls them member variables and member functions because they are members of a class. Much of the following syntax has to do with creating objects, accessing data, and calling operations.

Constructors

Constructors are just functions (C++) or methods (Java), but they are special in one significant way. Each time a program instantiates a new object, it automatically calls a constructor that builds or initializes the object making it ready for use by the program. Constructors can be simple or complex. Simple constructors may simply initialize the variables in an object by transferring the values stored in the constructor arguments to the variables. Complex constructors may perform more complicated operations.

Creating or instantiating a new object in C++ is similar to instantiating an object in Java, but there are some important differences. Suppose that we have a class named Foo and we wish to instantiate a Foo object. Assume that class Foo has a constructor that does not take any arguments. The instantiation statements look like this:

Foo myFoo1 = new Foo();		// Java
Foo* myFoo2 = new Foo;		// C++
Foo myFoo3;			// C++
Instantiating an object with a zero-argument constructor. Java provides one way for creating an object while C++ provides two ways. C++ requires more symbols or operators than does Java because it has more options. The options make C++ more flexible but at the expense of having a more complex syntax. Together, the class name and the asterisk create a pointer variable.

We begin to understand why C++ is a more complex language than Java with this example: C++ has more ways of creating objects than Java. Note the use of the asterisk ( * ) in conjunction with the class name when the new keyword is used in C++. The asterisk modifies the variable myFoo2 making it a pointer, which we cover in chapter 3. Unlike Java, C++ does not require parentheses when the constructor does not have any arguments (previously, C++ didn't allow parentheses, but they are optional now). We will explore the differences between the two ways of creating objects in C++ in chapter 4. If the constructor does require an argument, then the parentheses are needed:

Foo myFoo1 = new Foo(5);	// Java
Foo* myFoo2 = new Foo(5);	// C++
Foo myFoo3(5);   		// C++
Instantiating an object with a one-argument constructor. Adding arguments to constructors does not change the number of options for instantiating objects: one way for Java and two ways for C++. The figure illustrates the options with a one-argument constructor.

General Method and Function Calls

Now let's suppose that the Foo class has a method or function named doSomething. C++ has two ways of creating an object, which requires two ways to use the object, which in turn requires an operator not found in Java. The new operator, called arrow, is formed by the minus and greater than symbols together without any space and is used whenever the variable to the left is a pointer. Otherwise, both languages use the dot operator to make the call.

myFoo1.doSomething();    // Java
myFoo2->doSomething();   // C++
myFoo3.doSomething();    // C++, looks like Java
Calling a method or function defined inside of a class.

Many Java textbooks claim that Java doesn't have pointers. Nevertheless, Java program always manage all objects with pointers (technically references). However, Java only has one way of managing objects, so it dispenses with the pointer operators that we will tackle in chapter 4.

Arrays

Strictly speaking, arrays are not an object-oriented construct. However, Java implements them as objects, while C++ treats them as a primitive or fundamental data type. The difference between the two languages warrants a brief comparison, which should be sufficient until we formally study arrays in chapter 7.

Conceptually and functionally, an array is a collection of variables managed by a common name. Individual variables, called elements, within the array are selected by an index or subscript. Arrays have a size, which is the number of elements or variables that they hold. Programs determine the size of each array when it creates them. C++ and Java implement zero-indexed arrays, which means that valid array index values range from 0 to the size of the array - 1. All of the variables in the array must be the same data type (e.g., int or double). The following figure demonstrates how programmers create arrays in C++ and Java. The figure also shows an abstract representation of an array in computer memory.

(a)
double[] scores = new double[8];
(b)
double scores[8];
double* scores = new double[8];
(c) An array represented as a large rectangle subdivieded into eight smaller rectangles. The smaller rectangles represent the eight array elements. The illustration includes the array index values, 0, 1, 2, ..., 7 adjacent to the smaller, element rectangles.
Creating an array in Java and in C++. Arrays are a common data structure that are supported by most programming languages. An array capable of holding eight double values is illustrated here.
  1. In Java, an array is an instance of an unnamed class that is always created with the new operator. (The java.util.Arrays class contains a collection of static methods that are useful when working with arrays but is not involved with creating arrays.)
  2. Arrays may be created in two different ways in a C++ program. The second way is very similar (both in appearance and in the underlying concepts) to what is done in Java. The difference between the two statements is explored in greater detail in chapter 4.
  3. Arrays created in both languages have a similar appearance. The illustrated array has eight double variables or elements that are are accessed as scores[0], scores[1],scores[2], ..., scores[7].
Java arrays have a length attribute, which is possible because Java arrays are objects. However, C++ arrays are NOT objects and do NOT have a length attribute. So, for example, based on Figure 5(a), you may write scores.length in a Java program but not in a C++ program.