Microsoft & .NET.NETLearning C# and OOP, Classes

Learning C# and OOP, Classes

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

C# Programming Notes # 104


Preface

This is the second lesson in a miniseries designed to teach you how to write object-oriented programs using C#.  This miniseries will describe and discuss the necessary and significant aspects of object-oriented programming (OOP) using C#.

The first lesson in the miniseries was entitled Learning C# and OOP: Getting Started, Objects and Encapsulation.

Comparisons with Java

The miniseries will also make comparisons between C# and Java with respect to both syntax and OOP concepts.  I will emphasize the similarities between these two programming environments, which are likely to dominate the programming world in the foreseeable future.  By studying these lessons and learning about OOP using C#, you will also be learning quite a lot about OOP using Java.

Relatively high level

I will provide the information in a high-level format, devoid of any prerequisite requirement to know C# syntax.  In those cases where an understanding of C# syntax is required, I will provide the necessary syntax information in the form of sidebars and sample programs.

Therefore, if you have a general understanding of computer programming, you should be able to read and understand the lessons in this miniseries, even if you don’t have a background in object-oriented programming, or a background in the C# programming language.

Viewing tip

You may find it useful to open another copy of this lesson in a separate browser window.  That will make it easier for you to scroll back and forth among the different listings while you are reading about them.

Supplementary material

I recommend that you also study the other lessons in my extensive collection of online programming tutorials.  You will find those lessons published at developer.com.  However, as of the date of this writing, developer.com doesn’t maintain a consolidated index of my tutorial lessons, and sometimes they are difficult to locate there.  You will find a consolidated index at www.DickBaldwin.com.

Preview

Concentrate on classes

This lesson will concentrate primarily on a discussion of the C# class, and a comparison of a C# class with a similar Java class.

A simple C# program will be developed to illustrate the definition and use of two different classes.  Taken in combination, these two classes simulate the manufacture and use of the car radio object discussed in the previous lesson.

Instance variables and instance methods

You will see the definition of a C# class named Radio.  This class includes one instance variable and two instance methods. (The instance variable is a reference variable that refers to a special kind of object that I call an array object.  I will provide a very brief discussion of array objects in this lesson.  I will have more to say about array objects in a future lesson.)

Creating a new object

You will learn how to write code to create a new Radio object by applying the new operator to the constructor for a C# class named Radio.  You will also learn how to save that object’s reference in a reference variable of type Radio.

Defining methods

You will learn how to write C# code that is used to simulate the association of a radio button with a particular radio station.

You will learn how to write C# code that is used to simulate the pressing of a radio button to play the radio station associated with that button.

The Main method

You will see the definition of a C# class named Radio01.  This class consists simply of the Main method.  You will learn that the Main method of a C# program is executed by the C# Common Language Runtime (CLR) when the program is run.  Thus, the Main method is the driver for the entire program.

Comparison with Java code

In addition, you will learn how to write Java code to perform the tasks described above.  You will learn about the similarities and differences between the C# code and the Java code.  You will learn that at this level, there is very little difference between C# and Java.

Static variables

I will provide a short discussion of static variables, which are not used in this program.  I will explain that the use of static variables can often lead to undesirable side effects.

General class-definition syntax

Finally, I will provide a very brief discussion of the general syntax of a simple class definition in C#.

Discussion and Sample Code

What is a class?

A class is a plan from which many objects can be created.  In an earlier lesson, I likened the class definition to the plans from which millions of nearly identical car radios can be manufactured.

A simple C# program

In this lesson, I will provide and discuss a simple C# program.  This will help to get you started on the right foot.  I will also compare this simple C# program with a Java program designed to accomplish the same purpose.  This will illustrate the similarity of these two programming environments.

The complete C# program is shown in Listing 11, near the end of the lesson.  This program simulates the manufacture and use of a car radio.  The complete Java program is shown in Listing 12 near the end of the lesson.

Explain in fragments

In order to help you to focus specifically on important sections of code, I will explain the behavior of this program in fragments.

Top-level classes

This program contains two top-level class definitions. (C# also supports inner classes in addition to top-level classes.  As the name implies, an inner class is a class that is defined inside another class.  I will defer the discussion of inner classes until a future lesson.)

The class named Radio01

One of the top-level class definitions, named Radio01, is shown in its entirety in Listing 1.  (I will show you a Java class definition designed for the same purpose, and discuss the similarities and differences between the two class definitions later.)
 

public class Radio01{
  public static void Main(){
    Radio myRadio = new Radio();
    myRadio.setStationNumber(3,93.5);
    myRadio.playStation(3);
  }//end Main
}//end class Radio01

Listing 1

The Main method

The class named Radio01 consists simply of the Main method.  As is the case in C++ and Java, the Main method of a C# program is executed by the C# Common Language Runtime (CLR) when the program is run.  Thus, the Main method is the driver for the entire program.

What is the CLR?

According to Programming C#, by Jesse Liberty,

“The most important component of the .NET Framework is the CLR, which provides the environment in which programs are executed.  The CLR includes a virtual machine, analogous in many ways to the Java virtual machine.  At a high level, the CLR activates objects, performs security checks on them, lays them out in memory, executes them, and garbage-collects them.”

The driver class

An object instantiated from the code in Listing 1 simulates the manufacture of the radio and the use of the radio by the end user.

Without getting into a lot of detail regarding C# syntax at this point, I will further subdivide and discuss the code from Listing 1 in the following listings.

Constructing a Radio object

In C++, Java, and C#, new objects are constructed through the use of the new operator (C++ has other options as well).  The code in Listing 2 applies the new operator to the constructor for the Radio class, causing a new object to be created according to the plans specified in the Radio class.
 

     Radio myRadio = new Radio();

Listing 2

Saving a reference to the Radio object

The code in Listing 2 also declares a reference variable of type Radio, (named myRadio) and stores the new object’s reference in that variable.  The single statement in Listing 2 is analogous to manufacturing a new radio and installing it in your car, ready for use.

Programming the radio buttons

The code in Listing 3 simulates the process of associating a particular radio station with a particular button.  As I explained in the previous lesson, this is accomplished for my car radio by manually tuning the radio to a desired station and then holding the radio button down until it beeps.

You have probably done something similar to the radio in your car.
 

     myRadio.setStationNumber(3,93.5);

Listing 3

Not the only way to do this

Note that the approach used in Listing 3 is the approach that is commonly used in both C++ and Java.  This approach also works properly when used with C#.  However, this is not the only way to accomplish this task in C#.  Unlike C++ and Java, C# also provides a somewhat more cryptic approach, often referred to as a property indexer, to accomplish the same task.  I will explain properties and indexers in the next two lessons.

Invoke a method

The statement in Listing 3 accomplishes the association of a simulated radio button with a simulated radio station by invoking the method named setStationNumber on the reference to the Radio object.

This method takes two parameters.  I will show you the code for the method shortly.  In the meantime, the parameters passed to the method in this case cause radio button number 3 to be associated with the frequency 93.5 MHz. (The method causes the value 93.5 to be stored in the instance variable of the Radio object that represents button number 3.)

Sending a message to the object

Using typical OOP jargon, the statement in Listing 3 sends a message to the Radio object, asking it to change its state according to the values passed as parameters.

Pressing a button on the radio

Finally, the code in Listing 4 invokes the method named playStation on the Radio object, passing the integer value 3 (the button number) as a parameter.  This simulates pressing a button on the front of the radio to select a particular station.
 

    myRadio.playStation(3);

Listing 4

Another message

This code sends a message to the Radio object asking it to perform an action.

In this case, the action requested by the message is:

  • Tune yourself to the frequency previously associated with button number 3.
  • Play the radio station that you find at that frequency through the speakers.

How does this simulated radio play?

This simple program doesn’t actually play music.  As we will see later, invocation of the playStation method in Listing 4 causes the following message to appear on the computer screen.  This is intended to simulate the selection and playing of a specific radio station.

Playing the station at 93.5 Mhz

Comparison with Java

Listing 5 shows the definition of a Java class designed to perform exactly the same tasks as the C# class shown in Listing 1
 

public class Radio01{
  public static void main(
                       String[] args){
    Radio myRadio = new Radio();
    myRadio.setStationNumber(3,93.5);
    myRadio.playStation(3);
  }//end main
}//end class Radio01

Listing 5

If you are interested in learning Java along with C#, compare Listing 5 with Listing 1.  If not, simply skip the sections in these tutorial lessons that compare C# to Java.

If you compare Listing 5 with Listing 1, you will see that the only difference between the two is the boldface material shown in Listing 5.

Case-sensitive code

To begin with, C++, Java, and C# all require a main method.  In case I haven’t mentioned it before, C++, Java, and C# are all case sensitive.  That is to say, a method named main is not the same as a method named Main.

Upper-case M required for Main method in C#

C# requires the name of its Main method to begin with an upper-case character, while Java requires the name of its main method to begin with a lower-case character.  (C++ also requires the name of its main method to begin with a lower-case character, so C# is the odd ball in this trio of programming languages. )

Arguments to the main method

C++, Java, and C# all support the use of command-line arguments.  Command-line arguments are arguments that are entered by the user immediately following the name of the program when the program is started from the command line.

Java has a single signature for the main method

Java has only one signature for the main method.  The same signature is required whether or not it is intended that command-line arguments will be used.  Listing 5 shows that the arguments are passed in an array of type String to the main method of a Java program.  If no arguments are passed, the array will be empty.  If there is no intent to use command-line arguments, the code in the main method is written to ignore the incoming parameter.

C# has different signatures for the Main method

On the other hand, both C++ and C# have different signatures for the Main method.  The signature shown in Listing 1 (the signature with empty parentheses) is the signature used when there is no intent to make use of command-line arguments.

The signature used by C# for the support of command-line arguments is as follows:

public static void Main(string args)

This signature is discussed on page 11 of C# Primer, A Practical Approach, by Lippman.

You will note that this signature is markedly similar to the Java signature for the main method shown in Listing 5.

(The name of the string type in C# begins with a lower-case character instead of an upper-case character.  It is also true that the name of the string class in the ANSI/ISO C++ standard library begins with a lower-case character.  All class and interface names in the standard Java library begin with an upper-case character.)

No conceptual differences so far

To this point, we haven’t identified any conceptual differences between C# and Java.  The only differences so far are minor differences in the spelling of method and class names.  However, we will identify a few conceptual differences as we pursue this miniseries.

The Radio class

Listing 6 shows the class definition for the Radio class in its entirety.  (I will show you a comparative Java class designed for the same purpose later.)
 

class Radio{
  protected double[] stationNumber = 
                         new double[5];
                            
  public void setStationNumber(
                int index,double freq){
    stationNumber[index] = freq;
  }//end method setStationNumber
  
  public virtual void playStation(
                            int index){
    System.Console.WriteLine(
            "Playing the station at " 
               + stationNumber[index]
               + " Mhz");
  }//end method playStation
  
}//end class Radio

Listing 6

Constructors

A constructor is a special form of method that assists in the construction of an object, and the initialization of the data encapsulated by the object.  A class definition may, or may not, include an explicit constructor.

The code in Listing 6 does not contain an explicit constructor.  If you don’t define an explicit constructor when you define a new class, a default version of the constructor is provided on your behalf.  That is the case for this simple program.

The plans for an object

The code in Listing 6 provides the plans from which an object that simulates a physical radio can be constructed.

An object instantiated (an object is an instance of a class) from the code in Listing 6 simulates a physical radio.  I will subdivide this code into fragments and discuss it in the following listings.

An instance variable

In a previous lesson, I explained that we often say that an object is an instance of a class.  (A physical radio is one instance of the plans used to produce it.)

The code in Listing 7 shows the declaration and initialization of what is commonly referred to as an instance variable.
 

  protected double[] stationNumber = 
                         new double[5];

Listing 7

Why call it an instance variable?

The name instance variable comes from the fact that every instance of the class (object) has one.  (Every radio produced from the same set of plans has the ability to store a frequency value associated with each selector button on the front of the radio.)

Static variables – an aside

Note that C# also supports something called static variable, static data members, or class variable, which are different from instance variables.  See page 48 of C# In A Nutshell, by Drayton, Albabari, and Neward.

Static variables are shared among all of the objects instantiated from a given class.  Stated differently, no matter how many objects are instantiated from a class definition, they all share a single copy of each static variable.

There is no analogy to a static variable in a physical radio object.  Radios are installed in different cars separated from each other by thousands of miles.  Therefore, there can be no sharing of anything among different physical radio objects.

Static variables can cause undesirable side effects

While static variables are relatively easy to use, they are difficult to explain from an OOP viewpoint.

Also, it is my opinion that from a good overall design viewpoint, static variables should be used very sparingly, if at all.

Therefore, for the first several lessons in this series, I will exclude the possibility of static variables.  I will explain the use of static variables in C# in a future lesson.

Reference to an array object

Now, let’s get back to the instance variable named stationNumber shown in Listing 7.  Without getting into a lot of detail, this instance variable is also a reference variable.  That means that it is a variable capable of holding a reference to an object.  Following the execution of the statement in Listing 7, the reference variable named stationNumber contains a reference to an array object.

The array object encapsulates a simple one-dimensional array with five elements of type double(C# array indices begin with zero, so the index values for this array extend from 0 to 4 inclusive.)

A fairly complex topic

The overall topic of array objects in C# is a fairly complex topic.  I will also discuss array objects in more detail in a future lesson.  For now, suffice it to say that the five-element array object of type double is created using the new operator and the double data type in the following expression from Listing 7:

new double[5]

Once the array object has been created, that object’s reference is assigned to the reference variable named stationNumber.  The reference variable can be used later to access the elements of the array.

protected access control

Accessibility to instance variables, and other members of an object, can be restricted by the use of access-control keywords such as protected.  This is also a fairly complex topic, which I will defer to a future lesson.  For the time being, just ignore the use of the protected keyword in Listing 7.

Persistence

The array object is where the data is stored that associates the frequency of a radio station with a simulated physical button on the front of the radio.

Each element in the array corresponds to one frequency-selector button on the front of the radio.  Hence, the radio simulated by an object of the Radio class has five simulated frequency-selector buttons.

The array object is created by the code in Listing 7, and exists when the code in Listing 7 has finished executing.  Each element in the array is initialized to a value of 0.0 (double-precision float value of zero) when the array object is created.

The setStationNumber method

Listing 8 shows the setStationNumber method in its entirety
 

  public void setStationNumber(
                int index,double freq){
    stationNumber[index] = freq;
  }//end method setStationNumber

Listing 8

Associates radio station with button

This is the method that is used to simulate the behavior of having the user associate a particular button with a particular radio station. (Recall that this is accomplished on my car radio by manually tuning the radio to a specific station and then holding the button down until it beeps.  Your car radio probably operates in some similar way.)

This method receives two incoming parameters:

  • An integer (type int) that corresponds to a button number (button numbers are assumed to begin with 0 and extend through 4 in order to match the array indices)
  • A frequency value of type double to be associated with the indicated button.

Save the frequency value

The code in the method named setStationNumber stores the frequency value in an element of the array object discussed earlier.  The element number is specified by the value of index shown in square brackets on the left side of the assignment expression. (This syntax is similar to storing a value in an array element in most programming languages with which I am familiar.)

Pressing a radio button to select a station

Listing 9 shows the playStation method.  This is the method that simulates the result of having the user press a button on the front of the radio to select a particular radio station for play.
 

  public virtual void playStation(
                            int index){
    System.Console.WriteLine(
            "Playing the station at " 
               + stationNumber[index]
               + " Mhz");
  }//end method playStation

Listing 9

Selecting and playing a radio station

This method receives an integer index value as an incoming parameter.  This index corresponds to the number of the button pressed by the user.

This method simulates the playing of the radio station by extracting the appropriate frequency value from the array object (see the expression in bold Italics) and displaying that value on the computer screen along with some surrounding text.

When invoked by the code in the Main method of this program, this method produces the following message on the computer screen:

Playing the station at 93.5 Mhz

Comparison with Java

Listing 10 shows the Java code that corresponds to the C# code in Listing 6.
 

class Radio{
  protected double[] stationNumber = 
                         new double[5];
                            
  public void setStationNumber(
                int index,double freq){
    stationNumber[index] = freq;
  }//end method setStationNumber

  //C# declares this method virtual  
  public void playStation(int index){
    System.out.println(
            "Playing the station at " 
               + stationNumber[index]
               + " Mhz");
  }//end method playStation
  
}//end class Radio

Listing 10

The minor differences between C# and Java, at this level, can be discerned by comparing Listing 10 with Listing 6.  Those differences are highlighted in boldface in Listing 10.

Declaring a method virtual

As you can see, there are no differences in the C# and Java class definitions down to the signature of the method named playStation.  As indicated in the boldface comment in Listing 10, the C# class definition declares the method virtual whereas the Java class definition doesn’t declare it virtual.

Here we encounter our first minor conceptual difference between C# and Java.

What is a virtual method?

I’m not going to go into the details of virtual methods at this point, because I will be discussing the use of virtual methods in great detail in a future lesson.  For now, suffice it to say that virtual methods can be overridden.  Non-virtual methods cannot be overridden.  Method overriding provides a form of runtime polymorphism (recall the three pillars of OOP:  encapsulation, inheritance, and polymorphism).

So, what is the conceptual difference involved here?

The conceptual difference is that all methods in Java are virtual by default.  They must be declared final to prevent them from being virtual.  Methods in C# (and also in C++) are not virtual by default.  Rather, they must be declared virtual to cause them to be virtual.  Otherwise, they are non-virtual and cannot be overridden.

As you can see, this conceptual difference is minor, but it does have a significant impact on the C# programmer.  The C# programmer must decide at the point in time when the class is defined if there will ever be a need to override each method defined in the class definition.  If so, those methods that may later be overridden must be declared virtual.  Otherwise, it may not be possible to extend the class in an effective manner later.

Does not override the method

Note that even though the playStation method is declared virtual in this C# program, the method was not overridden in this program.  Rather, the method was declared virtual in preparation for extending the Radio class in a future lesson.  That is often the case when defining classes and methods in C#.

Console display

The only other difference between the class definitions in Listing 6 and Listing 10 is the expression used to display some text on the system console (standard output device).

C# uses the following expression to display text on the system console:

System.Console.WriteLine

Java uses the following expression to display text on the system console:

System.out.println

As you can see, these are very similar expressions.  The differences are minor, having to do with the way that the class libraries are organized in the two systems.  This is the kind of difference where a simple search-and-replace operation in an editor can be used to convert a program from one language to the other.

The bottom line on the comparison

To this point, the differences that we have seen between C# and Java are very minor.  However, we will see some other differences that have more substance as we continue through this series of lessons.

Class definition syntax

Now back to the general subject of object-oriented programming.  There are a number of items that can appear in a class definition, including the following:

  • Instance variables
  • Class or static variables
  • Instance methods
  • Class or static methods
  • Constructors
  • Inner classes

Let’s keep it simple

In order to make these lessons as easy to understand as possible, the first several lessons will ignore the possibility of static variables, static methods, and inner classes.

As mentioned in the earlier discussion, static variables aren’t particularly difficult to use, but they create a lot of complications when attempting to explain OOP from the viewpoint of C# programming.

Therefore, the first several lessons in the series will assume that class definitions are limited to the following items:

  • Instance variables
  • Instance methods
  • Constructors

A constructor

A constructor is used only once in the lifetime of an object.  It participates in the task of creating (instantiating) and initializing the object.  Following instantiation, the state and behavior of an object depends entirely on variables and methods.

Instance variables and methods

The class named Radio discussed earlier contains one instance variable named stationNumber, and two instance methods named setStationNumber and playStation.

Summary

This lesson has concentrated primarily on a discussion of the C# class, and a comparison of a C# class with a similar Java class.

A simple C# program was developed to illustrate the definition and use of two different classes.  Taken in combination, these two classes simulate the manufacture and use of a car radio object.

You saw the definition of a C# class named Radio.  This class includes one instance variable and two instance methods.  (The instance variable is a reference variable that refers to a special kind of object that I call an array object.  I provided a very brief discussion of array objects.  I will have more to say about array objects in a future lesson.)

You learned how to write code to create a new Radio object by applying the new operator to the default constructor for the C# class named Radio.  You also learned how to save that object’s reference in a reference variable of type Radio.

You learned how to write code (in an instance method named setStationNumber) used to simulate the association of a radio button with a particular radio station.

You learned how to write code (in an instance method named playStation) to simulate the pressing of a radio button to play the radio station associated with that button.

You saw the definition of a C# class named Radio01.  This class consists simply of the Main method.  You learned that the Main method of a C# program is executed by the C# Common Language Runtime when the program is run.  You learned that the Main method is the driver for the entire program.

In addition, you learned how to write Java code to perform the tasks described above.  You learned about the similarities and differences between the C# code and the Java code.  You learned that at this level, there is very little difference between C# and Java.

I provided a short discussion of static variables.  I explained that the use of static variables can often lead to undesirable side effects.

Finally, I provided a very brief discussion of the general syntax of a simple class definition in C#.

What’s Next?

In order to understand OOP, you must understand the following three concepts:

  • Encapsulation
  • Inheritance
  • Polymorphism

The discussion to this point has been restricted to encapsulation (the class is the primary mechanism for accomplishing encapsulation).

The next topic in the above list is inheritance.  However, before discussing inheritance, I am going to teach you about C# properties, and also teach you how to rewrite the program from this lesson using a C# property indexer.

Therefore, properties and indexers will be the topics of the next two lessons.  The rewrite of the above program to use an indexer will be slightly more cryptic than the version shown in this lesson.  However, many C# programmers use indexers, so you need to recognize that syntax.

Complete Program Listings

A complete listing of the C# program discussed in this lesson is shown in Listing 11.
 

/*File Radio01.cs
Copyright 2002, R.G.Baldwin
Simulates manufacture and use of a 
car radio.

This program produces the following
output on the computer screen:
  
Playing station at 93.5
**************************************/

public class Radio01{
  //This class simulates the 
  // manufacturer and the human user
  public static void Main(){
    Radio myRadio = new Radio();
    myRadio.setStationNumber(3,93.5);
    myRadio.playStation(3);
  }//end Main
}//end class Radio01
  //---------------------------------//

class Radio{
  //This class simulates the plans from
  // which the radio object is created.
  protected double[] stationNumber = 
                         new double[5];
                            
  public void setStationNumber(
                int index,double freq){
    stationNumber[index] = freq;
  }//end method setStationNumber
  
  public virtual void playStation(
                            int index){
    System.Console.WriteLine(
            "Playing the station at " 
               + stationNumber[index]
               + " Mhz");
  }//end method playStation
  
}//end class Radio

Listing 11

A complete listing of the Java program discussed in this lesson is shown in Listing 12.
 

/*File Radio01.java
Copyright 2002, R.G.Baldwin
This Java program is designed to show
the similarities between Java and C#.

This program produces the following
output on the computer screen:
  
Playing station at 93.5
**************************************/

public class Radio01{
  //This class simulates the 
  // manufacturer and the human user
  public static void main(
                       String[] args){
    Radio myRadio = new Radio();
    myRadio.setStationNumber(3,93.5);
    myRadio.playStation(3);
  }//end main
}//end class Radio01
  //---------------------------------//

class Radio{
  //This class simulates the plans from
  // which the radio object is created.
  protected double[] stationNumber = 
                         new double[5];
                            
  public void setStationNumber(
                int index,double freq){
    stationNumber[index] = freq;
  }//end method setStationNumber
  
  public void playStation(int index){
    System.out.println(
            "Playing the station at " 
               + stationNumber[index]
               + " Mhz");
  }//end method playStation
  
}//end class Radio

Listing 12

Review Questions

Note that some of the questions in this section may introduce new material not covered in the body of the lesson.

1.  True or false?  A class is a plan from which many objects can be created.

Answer

2.  True or false?  All C# classes are top-level classes.

Answer

3.  What output is produced by the following program?

  • A.  Compiler or Runtime Error
  • B.  Hello C# World
  • C.  None of the above.

/*File Q0001.cs
**************************************/
public class Q0001{
  public static void main(){
    System.Console.WriteLine(
                     "Hello C# World");
  }//end Main
}//end class Q0001
//===================================//

Answer

4.  What output is produced by the following program when it is compiled and then run by simply entering the name of the program at the command line prompt?

  • A.  Compiler Error
  • B.  Runtime Error
  • C.  Hello C# world
  • D.  None of the above.

/*File Q0002.cs
**************************************/
public class Q0002{
  public static void Main(
                        string[] args){
    System.Console.WriteLine(args[1]);
  }//end Main
}//end class Q0002
//===================================//

Answer

5.  What output is produced by the following program when it is compiled and then run by simply entering the following at the command line prompt?

Q0002 Hello C# world

  • A.  Compiler Error
  • B . Runtime Error
  • C.  Hello C# world
  • D.  None of the above.

/*File Q0002.cs
**************************************/
public class Q0002{
  public static void Main(
                        string[] args){
    System.Console.WriteLine(args[1]);
  }//end Main
}//end class Q0002
//===================================//

Answer

6.  Describe the behavior of the following C# statement:

Radio myRadio = new Radio();

Answer

7.  True or false?  The only way to set the value of an indexed property in C# is to invoke a method similar to that shown in the following statement, passing the index value and the new property value as parameters:

myRadio.setStationNumber(3,93.5);

Answer

8.  What output is produced by the following program?

  • A.  Compiler or Runtime Error
  • B.  Hello Java World
  • C.  None of the above.

/*File Q0003.java
**************************************/
public class Q0003{
  public static void main(){
    System.out.println(
                   "Hello Java World");
  }//end Main
}//end class Q0003
//===================================//

Answer

9.  True or false?  All class definitions must provide an explicit constructor.

Answer

10.  What is the primary characteristic of an instance variable?

Answer

11.  True or false?  C# array indices always begin with 1.

Answer

12.  Give a brief description of the use of the virtual keyword in C#, and compare it with the use of the virtual keyword in Java.

Answer



Richard Baldwin is a college professor (at Austin Community College in Austin, Texas) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects, and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin’s Programming Tutorials, which has gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin@DickBaldwin.com


Answers

Answer 12

To begin with, there is no virtual keyword in Java, so the second part of this question is easy.  The virtual keyword is never used in Java.

For now, suffice it to say that virtual methods can be overridden while non-virtual methods cannot be overridden.  Method overriding provides a form of runtime polymorphism (recall the three pillars of OOP:  encapsulation, inheritance, and polymorphism).  I will discuss method overriding in detail in future lessons.

There is a conceptual difference between C# and Java with respect to virtual methods.  All methods in Java are virtual by default. (They must be declared final to prevent them from being virtual.)

Methods in C# (and also in C++) are not virtual by default.  Rather, they must be declared virtual to cause them to be virtual.  Otherwise, they are effectively final (unable to be overridden) although there is no final keyword in either C# or C++.

This conceptual difference is minor, but it does have a significant impact on the C# programmer.  The C# programmer must decide when the class is defined if there will ever be a need to override each method defined in the class.  If so, those methods must be declared virtual when the class is defined.  Otherwise, it may not be possible to extend the class in an effective manner later.

Back to Question 12

Answer 11

False

Explanation 11

C# array indices always begin with 0 (zero).

Back to Question 11

Answer 10

The name instance variable comes from the fact that every instance of the class (object) has one.  As a result, a specific instance variable belongs to a specific object, and can only be accessed by way of the object to which it belongs.  There is no sharing of instance variables among objects.

Back to Question 10

Answer 9

False

Explanation 9

A constructor is a special form of method that assists in the construction of an object and the initialization of the data encapsulated by the object.  A class definition may, or may not, include an explicit constructor. If you don’t define an explicit constructor when you define a new class, a default version of the constructor is provided on your behalf.

Back to Question 9

Answer 8

A.  Compiler or Runtime Error

Explanation 8

The signature of the main method in a Java program must provide for the use of command-line arguments, whether or not it is intended that command-line arguments will be used in the program.  The signature of the main method in this program does not provide for command-line arguments (the formal argument list of the main method is empty).  While the program compiles OK, it produces the following error at runtime:

Exception in thread "main"
java.lang.NoSuchMethodError: main

Basically this means that the signature of the main method is incorrect.  This error is similar to the C# entry point error in Question 3.

Back to Question 8

Answer 7

False

Explanation 7

The approach shown in this question is the approach that is commonly used in both C++ and Java to modify the value of an indexed property.  The method is commonly called a setter method or a mutator method.  This approach also works when used with C# (although it may not be correct to refer to the value as a property value when this approach is used in C#).  However, this is not the only way to accomplish this task in C#.  Unlike C++ and Java, C# provides a somewhat more cryptic approach, often referred to as a property indexer, to accomplish the same task.  I will explain properties and indexers in the next two lessons.

Back to Question 7

Answer 6

The following statement applies the new operator to the constructor for the Radio class, causing a new object to be created according to the plans specified in the Radio class.

Radio myRadio = new Radio();

The above statement also declares a reference variable of type Radio, (named myRadio) and stores the new object’s reference in that variable.

Back to Question 6

Answer 5

D.  None of the above.

Explanation 5

Three separate command-line arguments are passed to the program when the program is run as described in this question.  Each command-line argument is a string.  The three strings end up residing in a three-element array of type string as shown in the following table:
 

Array Index
Array Contents
0
Hello
1
C#
2
world

This array is passed to the Main method.  Code in the Main method accesses and displays the string at array index 1, causing the following string to be displayed on the computer screen:

C#

Back to Question 5

Answer 4

B. Runtime Error

Explanation 4

The argument to the Main method is used to pass command-line arguments to the program.  As described in this question, the program was run with no command-line arguments.  Therefore, the array object of type string was empty when the program started running.  Code in the program attempted to access the contents of an array element producing the following runtime error:

Unhandled Exception: System.IndexOutOfRangeException:
Index was outside the bounds of
the array.
at Q0002.Main(String[] args)

Back to Question 4

Answer 3

A.  Compiler or Runtime Error

Explanation 3

C# is a case-sensitive language, and a method named main is not the same as a method named Main.  C# requires that the name of the Main method begin with an upper-case character.  The version of the .NET Framework that I am currently using produces the following compiler error:

error CS5001: Program 'Q0001.exe'
does not have an entry point defined

Back to Question 3

Answer 2

False

Explanation 2

C# also supports inner classes in addition to top-level classes.  As the name implies, an inner class is a class that is defined inside another class.  Inner classes weren’t discussed in this lesson.  That topic is being deferred until a future lesson.

Back to Question 2

Answer 1

True

Explanation 1

A class is a plan from which many objects can be created.  Object-oriented programmers believe that you should reuse rather than reinvent.  Once a class is defined, compiled, and distributed, it can be used over and over by different programmers with no requirement to recompile the class.  The standard C# class library contains thousands of compiled classes that were put there for your use.  In addition, you can always define a new class if the library doesn’t contain a class that meets your needs.

Back to Question 1



Copyright 2002, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

baldwin@DickBaldwin.com

-end-

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories