Chapter 7: Classes and Objects

Quiz Solutions

Solution to Question 7-1. A class defines a new type; an object is a single instance of that type.

Solution to Question 7-2. The keyword private indicates that access is limited to methods of the defining class.

Solution to Question 7-3. The keyword public indicates that access is available to methods in any class.

Solution to Question 7-4. When you create an instance of an object, the class’s constructor is called.

Solution to Question 7-5. A default constructor is a constructor that takes no parameters. If you do not create any constructor at all for your class, a default constructor is implicitly created.

Solution to Question 7-6. None. A constructor is not defined to return a type, and is not marked void.

Solution to Question 7-7. You can initialize the value of a member variable either in the constructor, using assignment, or when the member variable is created:

private int myVariable = 88;

Technically, only the latter is truly initialization; assigning it in the constructor is not as efficient.

Solution to Question 7-8. this refers to the object itself—the current instance of the class.

Solution to Question 7-9. A static method has no this reference. It does not belong to an instance; it belongs to the class and can call only other static methods.

You access a static method through the name of the class:

Dog myDog = new Dog(  );
myDog.InstanceMethod(  );
Dog.StaticMethod(  );

Of course, from within any method (including static methods), you can instantiate a class, and then call methods on that instance.

You can even instantiate an instance of your own class, and then call any nonstatic method of that object, as we did with (static) Main( ) calling (nonstatic) Test( ).

Solution to Question 7-10. Instances of classes are reference types and are created on the heap. Intrinsic types (such as integers) and structs are value types and are created on the stack.

Exercise Solutions

Solution to Exercise 7-1. Write a program with a Math class that has four methods: Add, Subtract, Multiply, and Divide, each of which takes two parameters. Call each method from Main( ) and provide an appropriate output statement to demonstrate that each method works. You don’t need to have the user provide input; just provide the two integers to the methods within Main( ).

This is a reasonably simple exercise; all you need to do is remember how to define a new class, and then write the various methods for it. The code for the methods is simple enough; you just have to make sure to choose parameters that you can understand. left and right make good parameter names for mathematical methods like these.

Then you have to write a brief Main( ) that declares an instance of the Math class, and then calls each method in turn, providing the appropriate parameters. You store the returned values in variables, and then output them to the console. We chose to use the numbers 3 and 5 for the operands, but you can use whatever you like. Example A-14 shows our solution to this exercise.

Example A-14. Our solution to Exercise 7-1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_7_1
{
   class Math
   {
       public int Add( int left, int right )
       {
         return left + right;
       }
       public int Subtract( int left, int right )
       {
           return left - right;
       }
       public int Multiply( int left, int right )
       {
           return left * right;
       }
       public float Divide( float left, float right )
       {
           return left / right;
       }
   }     // end class Math
   class Program
   {
       static void Main(  )
       {
           Math m = new Math(  );
           int sum =         m.Add(3,5);
           int difference =  m.Subtract(3,5);
           int product =     m.Multiply(3,5);
           float quotient =  m.Divide(3.0f, 5.0f);
           Console.WriteLine("sum: {0}, difference: {1}, product: {2},
                   quotient: {3}", sum, difference, product, quotient);
       }
   }
}

Solution to Exercise 7-2. Modify the program from Exercise 7-1 so that you do not have to create an instance of Math to call the four methods. Call the four methods again from Main( ) to demonstrate that they work.

The difference here is that you don’t want to create an instance of the Math class to do the work, which makes logical sense, since “math” isn’t a real-world object that you would normally model an instance of. That means you’ll need to use static methods to avoid creating an instance. The class stays mostly the same, except that you add the static keyword to each method name.

Now, in Main( ), instead of declaring an instance of Math, you can simply call the methods directly on the class, and do not create an instance first. In fact, the .NET Framework has a static Math class with methods for things like logarithms and trigonometric functions that you use in exactly this way. Example A-15 shows one solution.

Example A-15. One solution to Exercise 7-2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_7_2
{
    class Math
    {
        static public int Add( int left, int right )
        {
            return left + right;
        }
        static public int Subtract( int left, int right )
        {
            return left - right;
        }
        static public int Multiply( int left, int right )
        {
            return left * right;
        }
        static public float Divide( float left, float right )
        {
            return left / right;
        }
    }     // end class Math
    class Program
    {
        static void Main( string[] args )
        {
            int sum =         Math.Add( 3, 5 );
            int difference =  Math.Subtract(3,5);
            int product =     Math.Multiply(3,5);
            float quotient =  Math.Divide(3.0f, 5.0f);
            Console.WriteLine("sum: {0}, difference: {1}, product: {2},
                        quotient: {3}", sum, difference, product, quotient);
        }
    }
}

Solution to Exercise 7-3. Create a class Book that you could use to keep track of book objects. Each Book object should have a title, author, publisher, and ISBN (which should be a string, rather than a numeric type, so that the ISBN can start with a 0 or include an X). The class should have a DisplayBook( ) method to output that information to the console. In Main( ), create three Book objects with this data:

Programming C# 3.0      Jesse Liberty and Donald Xie        O'Reilly      9780596527433
C# 3.0 In a Nutshell    Joseph Albahari and Ben Albahari    O'Reilly      9780596527570
C# 3.0 Cookbook         Jay Hilyard and Stephen Teilhet     O'Reilly      9780596516109

Because all three books have the same publisher, you should initialize that field in your class.

The Book class is simple enough to create. The only difference in this exercise is that you have to initialize the publisher member to the string “O’Reilly” when you declare it, and then adjust your constructor accordingly. One solution is shown in Example A-16.

Example A-16. One solution to Exercise 7-3

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_7_3
{
    class Book
    {
        private string title;
        private string author;
        private string publisher = "O'Reilly";
        private string isbn;

        public void OutputBook(  )
        {
            Console.WriteLine("Title: {0}, Author: {1}, Publisher: {2},
                              ISBN: {3}", title, author, publisher, isbn);
        }

        //constructor
        public Book(string myTitle, string myAuthor, string myIsbn)
        {
            title = myTitle;
            author = myAuthor;
            isbn = myIsbn;
        }
    }

    class Program
    {
        static void Main(  )
        {
            Book firstBook = new Book("Programming C# 3.0",
                             "Jesse Liberty and Donald Xie", "9780596527433");
            Book secondBook = new Book("C# 3.0 In a Nutshell",
                             "Joseph Albahari and Ben Albahari", "9780596527570");
            Book thirdBook = new Book("C# 3.0 Cookbook",
                             "Jay Hilyard and Stephen Teilhet", "9780596516109");

            Console.WriteLine("First book:");
            firstBook.OutputBook(  );
            Console.WriteLine("Second book:");
            secondBook.OutputBook(  );
            Console.WriteLine("Third book:");
            thirdBook.OutputBook(  );
        }
    }
}

Solution to Exercise 7-4. You might think it isn’t possible to draw geometric shapes using the console output, and you’d be mostly right. We can simulate drawing shapes, though, by imagining a graph and displaying, say, the coordinates of the four corners of a square. Start with a class called Point. This is a simple enough class; it should have members for an x coordinate and a y coordinate, a constructor, and a method for displaying the coordinates in the form (x,y). For now, make the x and y members public, to keep things simple.

Now create a class Square. Internally, the class should keep track of all four points of the square, but in the constructor, you should accept just a single Point and a length (make it an integer, to keep it simple). You should also have a method to output the coordinates of all four points. In Main( ), create the initial Point, then create a Square and output its corners.

The difference in this exercise is that you’ll be using objects of one class (Point) as internal members of another class (Square). That’s not tricky, but the first time you do it, it may be unexpected. The Point class is simple enough to create; you just need two internal members; call them whatever you like. We suggested that you make the members public because the Square class will need to access them as well. There’s a better way to access the members of another class; you’ll learn that in Chapter 8.

public class Point
{
    public int xCoord;
    public int yCoord;
    public void DisplayPoint(  )
    {
        Console.WriteLine("({0}, {1})", xCoord, yCoord);
    }

    //constructor
    public Point(int x, int y)
    {
        xCoord = x;
        yCoord = y;
    }
}

Now that you have the Point class, you need four of them to make up the Square class. We specified that the constructor for the Square should take just one Point and a length. Therefore, the class needs to work out the other points and assign them to the internal members. We’ve done that in the constructor. You can access the x and y coordinates of the point you passed in to the constructor, add the length as appropriate, and generate the other three points:

public class Square
{
    private Point topLeft;
    private Point topRight;
    private Point bottomRight;
    private Point bottomLeft;
    private int sideLength;
    public void displaySquare(  )
    {
        Console.WriteLine("The four corners are:");
        topLeft.DisplayPoint(  );
        topRight.DisplayPoint(  );
        bottomLeft.DisplayPoint(  );
        bottomRight.DisplayPoint(  );
    }

    //constructor
    public Square(Point myPoint, int myLength)
    {
        sideLength = myLength;
        topLeft = myPoint;
        topRight = new Point(topLeft.xCoord + sideLength, topLeft.yCoord);
        bottomLeft = new Point(topLeft.xCoord, topLeft.yCoord + sideLength);
        bottomRight = new Point(topLeft.xCoord + sideLength, topLeft.yCoord +
                                sideLength);
    }
}

As always, there are many possible solutions, but one of them is shown in full in Example A-17.

Example A-17. One solution to Exercise 7-4

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Exercise_7_4
{
    public class Point
    {
        public int xCoord;
        public int yCoord;

        public void DisplayPoint(  )
        {
            Console.WriteLine("({0}, {1})", xCoord, yCoord);
        }

        //constructor
        public Point(int x, int y)
        {
            xCoord = x;
            yCoord = y;
        }
    }

    public class Square
    {
        private Point topLeft;
        private Point topRight;
        private Point bottomRight;
        private Point bottomLeft;
        private int sideLength;

        public void displaySquare(  )
        {
            Console.WriteLine("The four corners are:");
            topLeft.DisplayPoint(  );
            topRight.DisplayPoint(  );
            bottomLeft.DisplayPoint(  );
            bottomRight.DisplayPoint(  );
        }

        //constructor
        public Square(Point myPoint, int myLength)
        {
            sideLength = myLength;
            topLeft = myPoint;
            topRight = new Point(topLeft.xCoord + sideLength, topLeft.yCoord);
            bottomLeft = new Point(topLeft.xCoord, topLeft.yCoord + sideLength);
            bottomRight = new Point(topLeft.xCoord + sideLength,
                                        topLeft.yCoord + sideLength);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Point startPoint = new Point(3, 3);
            int length = 5;
            Square mySquare = new Square(startPoint, length);
            mySquare.displaySquare(  );
        }
    }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset