Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Creating and Using Classes, Methods, and Constructors in Object-Oriented Programming, Study notes of Computer Science

How to create your own classes in programming, which can store variables (data members) and functions (methods). The benefits of using methods include avoiding repeat code, promoting software reuse, and promoting good design practices. A template for defining methods and discusses access control using public and private modifiers. It also covers class constructors and using methods as accessors and mutators.

Typology: Study notes

2009/2010

Uploaded on 03/28/2010

koofers-user-7lp
koofers-user-7lp 🇺🇸

10 documents

1 / 10

Toggle sidebar

Related documents


Partial preview of the text

Download Creating and Using Classes, Methods, and Constructors in Object-Oriented Programming and more Study notes Computer Science in PDF only on Docsity! Classes, Methods, Constructors Writing Classes We’ve been using predefined classes and objects – how do we make our own? A class is defined using the following template. Essentially we can store two types of data in a class, variables (data members or fields), and functions (methods). A simple format for defining a class is given below; we will add some enhancements to it shortly. class className { // Define data members; i.e. variables associated with this class public/private type varname1; public/private type varname2; … public/private type varnameN; // Define methods; i.e. functions associated with this class public/private return_type methodName1(parameter_list); public/private return_type methodName2(parameter_list); … public/private return_type methodNameN(parameter_list); } To add a class in Visual Studio, select “P)roject” and “Add Class” from the menu: Each class is stored in its own file, visible in the Solution Explorer. The term “data member” refers to a variable defined in the class. Methods are functions defined in the class. A method is just a collection of code. The main method and button click events are all examples of methods. The parameter list is used to pass data to the method. Since a method is a function, we have to declare what type of value the function will return (e.g., int, float, long, etc.) If we don’t want the method to return any value, we have a special type called void. Class Methods or Functions So far, we have been working with relatively small programs using only a main function or several button click events. For larger programs the technique of dividing a program up into manageable pieces is typically done by constructing a number of smaller methods and then piecing them together as modules. This type of modularization has a number of benefits:  Avoids repeat code (reuse a method many times in one program)  Promotes software reuse (reuse a method in another program)  Promotes good design practices (Specify function interfaces)  Promotes debugging (can test an individual method to make sure it works properly) Let’s examine how to write programs using methods. Before starting We’ve already been using quite a few methods in our programs. Calls like WriteLine(), Show(), and rnd.Next() are all methods that have been written by someone else that we’re using. Note how the innards of these functions are all hidden from you – as long as you know the interface, or the input/output behavior, you are able to use these methods in your own programs. This type of data- hiding is one of the goals of methods and classes, so that higher-level code doesn’t need to know the details of particular tasks. Before starting and jumping into writing programs using methods, it is a good idea to look at the problem you are trying to address and see how it might logically be broken up. If you jump straight into coding you might not be defining methods that make sense and will have to throw away what you did and start over. Defining a Method To define a method use the following template: modifier return_type methodName(type1 varName1, type2 varName2, … ) { Instructions return (return_value); } Modifier is either public or private to indicate if this method is available from outside the class. Return_type is a data type returned by the method. For example, int, float, long, another Class, or void if we have no data to return. If we are returning a value, we must specify what value the method Write a program that plays the game of Craps using the rules stated above so that it simulates a game without human input. Use methods for rolling the dice and rolling for the point. Count the win % for 100,000 games. Example: Modify the Monty Hall solution to use a method(s) to determine which door to reveal instead of duplicating almost the same code across three button click events. Class Variables – Data Members We already know what variables are. Variables defined inside a class are called member variables, because they are members of a class. They are also referred to as fields. Member variables are accessible from code defined inside the class. If defined using public then member variables are also accessible from code defined outside the class. If defined using private then these variables are only accessible from code defined inside the class. Let’s look at a simple class that contains only data members and no methods. class Money { public int dollars; public int cents; } Now consider another class (say a Form with a button click event) that creates objects of type Money: private void button1_Click(object sender, EventArgs e) { Money m1 = new Money(); Money m2 = new Money(); m1.dollars = 3; m1.cents = 40; m2.dollars = 10; m2.cents = 50; Console.WriteLine(m1.dollars + " " + m1.cents); Console.WriteLine(m2.dollars + " " + m2.cents); } The output of this program is: 3 40 10 50 When the program reaches the print statement, we have created two separate instances of the Money object, each with different values stored in their member variables: dollars: 3 cents: 40 dollars: 10 cents: 50 m1 m2 This can be quite convenient, because we can now associate multiple variables together in a single object. While both of these variables were of type integer in this example, the types could be anything. For example, a class to represent an Employee might contain variables like the following: class Employee { string Name; int Age; double HourlyWage; long IDNumber; } In this way we are associating different variable types with the Employee object. This is a powerful construct to help organize our data efficiently and logically. Controlling Access to Data Members or Methods We can explicitly state whether or not access is granted by using the keywords public or private (there is another keyword, protected, which we won’t cover at this point). To use these modifiers, prefix the class variable with the desired keyword. Public means that this variable can be accessed from outside the class. Private means that this variable is only accessible from code defined inside the class. This designation can be useful to hide data that the implementer of the class doesn’t want the outside world to see or access. For example if we redefine our Money class: class Money { public int dollars; private int cents; } Then from another class’ button click event: private void button1_Click(object sender, EventArgs e) { Money m1 = new Money(); m1.dollars = 3; // Legal, dollars is public m1.cents = 40; // ILLEGAL, cents is private } This program will generate a compiler error since we are trying to access a private variable from outside the class. It is considered good programming style to always use public or private to indicate the access control of all class variables. We can also apply the public and private modifiers to methods as well as variables, as we will see next. Note that these modifiers only apply to variables defined in the class, not to variables defined inside a method (e.g., we won’t use private/public on variables defined inside a button click event). Class Constructors Because we use classes to encapsulate data types, it is essential that class objects be initialized properly. When we defined the Money class, we were relying upon the user to set the value for dollars and cents outside the class. What if the client forgets to initialize the values? This can be such a serious problem that Java provides a mechanism to guarantee that all class instances are properly initialized, called the class constructor. A class constructor is a method with the same name as the class and no return type. We can even make multiple constructors with multiple parameters, to differentiate different ways a class may be initialized. Below are two constructors for the Money class along with a method to get the currency value as a string: class Money { private int dollars = 0; private int cents = 0; // This constructor invoked if we create // the object with no parameters public Money() { dollars = 1; cents = 0; } // This constructor invoked if we create the object with // a dollar and cent value public Money(int inDollars, int inCents) { dollars = inDollars; cents = inCents; }
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved