Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
11/6/2018
EEE-425 Programming Languages (2013) 1
2
3
Learn about class concepts
How to create a class from which objects can be instantiated
Learn about instance variables and methods
How to declare objects
How to organize your classes
Learn about public fields and private methods
Learn about the this and base references
How to write constructor methods
How to pass parameters to constructors
How to overload constructors
How to write destructor methods
4
There are two distinct types of classes created in C#: ◦ Classes that contain a Main() method
◦ Classes from which you instantiate objects
Everything is considered an object in the object-oriented approach
Object-oriented programmers recognize “is-a relationships”
5
An object contains both data and methods that manipulate that data ◦ The data represent the state of the object
◦ Data can also describe the relationships between this object and other objects
Example: A CheckingAccount might have ◦ A balance (the internal state of the account)
◦ An owner (some object representing a person)
6
You could (in a game, for example) create an object representing a rabbit
It would have data: ◦ How hungry it is
◦ How frightened it is
◦ Where it is
And methods: ◦ eat, hide, run, dig
11/6/2018
EEE-425 Programming Languages (2013) 2
7
Every object belongs to (is an instance of) a class
An object may have fields, or variables ◦ The class describes those fields
An object may have methods ◦ The class describes those methods
A class is like a template, or cookie cutter ◦ You use the class’s constructor to make objects
8
An Abstract Data Type (ADT) bundles together: ◦ some data, representing an object or "thing"
◦ the operations on that data
The operations defined by the ADT are the only operations permitted on its data
Classes enforce this bundling together ◦ If all data values are private, a class can also enforce
the rule that its defined operations are the only ones permitted on the data
9 10
instance = object
field = instance variable
method = function
sending a message to an object = calling a function
These are all approximately true
11
Classes are arranged in a treelike structure called a hierarchy
The class at the root is named Object Every class, except Object, has a superclass A class may have several ancestors, up to
Object When you define a class, you specify its
superclass ◦ If you don’t specify a superclass, Object is assumed
Every class may have one or more subclasses
12
Container
Panel ScrollPane Window
Dialog Frame
FileDialog
A FileDialog is a Dialog is a Window is a Container
11/6/2018
EEE-425 Programming Languages (2013) 3
13
A class header or class definition contains three parts: ◦ An optional access modifier
◦ The keyword class
◦ Any legal identifier you choose for the name of your class
14
Private and protected classes have limited uses
When you declare a class using a namespace, you can only declare it to be public or internal
Class access is internal by default
15
Instance variables are created using the same syntax used to declare other variables
The allowable field modifiers are ◦ new, ◦ public, ◦ protected, ◦ internal, ◦ private, ◦ static, ◦ readonly, and ◦ volatile
16
Identifying a field as private means that no other class can access the field’s value, and only methods of the same class will be allowed to set, get, or otherwise use the field
Using private fields within classes is an example of information hiding
Although most fields are private, most class
methods are public
Public : Public is the most commonly used access specifier in C# . It can be access from anywhere, that means there is no restriction on accessibility. The scope of the accessibility is inside class as well as outside. The type or member can be accessed by any other code in the same assembly or another assembly that references it.
Protected : The scope of accessibility is limited within the class or struct and the class derived from this class. the members of Protected access specifier can be accessed
Internal :The internal access modifiers can access within the program that contain its declarations and also access within the same assembly level but not from another assembly.
Protected Internal : Protected internal is the same access levels of both protected and internal. It can access anywhere in the same assembly and in the same class also the classes inherited from the same class .
17 18
In the following code, the variable idNumber is private, yet remains accessible to outside classes through the GetId() method
Methods used with object instantiations are called instance methods
11/6/2018
EEE-425 Programming Languages (2013) 4
19
It creates a method that is a counterpart to the GetID() method, called SetId()
The SetId() method does not return any value, rather, it is used to assign a value in the class
20
Declaring a class does not create any actual objects
A two step process creates an object that is an instance of a class: ◦ Supply a type and an identifier
◦ Allocate computer memory for the object
Declaring an object notifies the compiler of the identifier and the type, but it does not allocate memory
21
To allocate the needed memory for an object, use the new operator
For example:
Employee myAssistant = new Employee();
The value being assigned to myAssistant is a memory address at which it will be located
Any class created can be referred to as a reference type, while the predefined types are called value types
The method called after the new keyword is called the constructor method
All code executes in a method ◦ Constructors, destructors and operators are special
types of methods
◦ Properties and indexers are implemented with get/set methods
Methods have argument lists
Methods contain statements
Methods can return a value
23
When you create an application that uses multiple class definitions, the class definitions can be stored in either a single file or each can be placed in its own file
Storing all class definitions in one file shortens development time and simplifies the compilation process
Using separate files for each class definition provides a more organized and manageable technique, and it allows for easier reusability
24
Most classes you create will have multiple methods and fields, which can become difficult to track in large programs
It is a good idea to arrange fields and methods in a logical order: ◦ Alphabetically
◦ By “Sets” and “Gets”
◦ Pairing of “Sets” and “Gets”
11/6/2018
EEE-425 Programming Languages (2013) 5
25
In addition to organizing fields and methods, comments should also be used
26
The private fields/public method arrangement ensures that data will be used and changed only in ways provided in your methods
Although it is easier to declare fields as public, doing so is considered poor object-oriented programming design
Data should always be hidden when possible and access should be controlled by well-designed methods
27
Poorly designed Desk class and program that instantiates a Desk
28
The Carpet class
29
Occasionally, there are instances where a data field should be declared as public
A data field may be declared public if all objects of a class contain the same value for that data field
The example declared a public const field
A named constant within a class is always static
30
When instances of a class are created, the resulting objects require separate memory locations in the computer
In the following code, each object of Book would at least require separate memory locations for title, numPages, and Price
11/6/2018
EEE-425 Programming Languages (2013) 6
31
Unlike the class fields that are unique to each instance, the methods of the class are shared
Although the methods are shared, there must be a difference between two method calls (from different objects), because each returns a different value (based on their unique fields)
When a method is called, you automatically pass a reference to the memory of the object into the method
The implicitly passed reference is the this reference
32
Book class methods explicitly using the this reference
33
Book class method that requires explicit this reference
34
http://www.c-sharpcorner.com/UploadFile/891f80/this-keyword-in-C-Sharp/
Classes support information hiding ◦ Data members of a class can be declared as private
Hides implementation details of the class
◦ Create accessor methods to access data Typically get__() and set__(), which are public
“Getters and setters”
◦ Other classes access data via get() and set() method So long as the interface to get and set stay the same,
the class can change how it represents its data
Information hiding permits implementations to change without affecting using classes
Provide procedural access to data ◦ Like accessors
But have syntax similar to direct variable access ◦ foo.X instead of foo.getX();
Minor feature, but provides substantial improvement in readability and fluidity of programming
Travis thumbs his nose at private property www.flickr.com/photos/sillygwailo/492070136/
11/6/2018
EEE-425 Programming Languages (2013) 7
Get accessor returns value of same type as “return type”
Set accessors have implicit parameter named “value” ◦ Use to set internal data representation
Properties can be public, private, protected ◦ Public: any class can access, private: only that class,
protected: that class and children
By convention, property names have initial capital (“X” to access “x”)
[access-modifiers] return-type property-name { get { … sequence of statements ending in a return (or throw) } set { … sequence of statements } }
get accessor
set accessor
using System;
namespace ConsoleApplication1
{
class Example
{
int _number;
public int Number
{
get
{
return this._number;
}
set
{
this._number = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Example example = new Example();
example.Number = 5; // set { }
Console.WriteLine(example.Number); // get { }
}
}
}
38
class access {// String Variable declared as private private static string name; public void print() { Console.WriteLine("\nMy name is " + name); } public string Name //Creating Name property { get //get method for returning value { return name; } set // set method for storing value in name field. { name = value; } }
class Program { static void Main(string[] args) { access ac = new access(); Console.Write("Enter your name:\t"); // Accepting value via Name property ac.Name = Console.ReadLine(); ac.print(); Console.ReadLine(); } }
public Example() // Set the private property.
{ this.IsFound = true; } bool found; public bool IsFound
{ get {
return this.found; } private set// Can only be called in this class. { this.found = value;
} } }
class Program { static void Main()
{ Example example = new Example(); Console.WriteLine(example.IsFound); }
}
40
using System;
namespace ConsoleApplication1
{
class Example
{
static int count;
public static int Count
{
get // Side effect of this property.
{
count++;
return count;
}
}
}
class Program
{
static void Main()
{
Console.WriteLine(Example.Count);
Console.WriteLine(Example.Count);
Console.WriteLine(Example.Count);
}
}
}
41
using System;
namespace ConsoleApplication1
{
class Example
{
public Example()
{ // Use private setter in the constructor.
this.Id = new Random().Next();
}
public int Id
{
get;
private set;
}
}
class Program
{
static void Main()
{
Example example = new Example();
Console.WriteLine(example.Id);
}
}
}
42
11/6/2018
EEE-425 Programming Languages (2013) 8
43
A constructor method is a method that establishes an object
Constructors have the following characteristics There is NO return type. NOT even void The method name is the same name as the class Constructors can be overloaded
In order to put the object into a usable state, its instance variables should be initialized to usable values
This could be accomplished by calling the various set methods This is not always possible because it is not required that all instance variables have set methods.
Constructors - Example using System; namespace ConsoleApplication1 { class test { int size; public test(int mysize) { size = mysize; } public void writeresult() { Console.WriteLine(size); } } class Program { static void Main() { test Mytest1 = new test(10); test Mytest2 = new test(20); Mytest1.writeresult(); Mytest2.writeresult(); } } }
45
You can create a constructor that sets the same value for all objects instantiated. The program can eventually call the method of the object to set the value. However, this might not always be the most efficient technique.
46
In this code, the constructor receives an argument and initializes the object with the appropriate information
47
C# automatically provides a default constructor
However if you create your own constructor, the automatically provided default constructor is not available
C# constructor methods, like other methods, can be overloaded
using System;
namespace ConsoleApplication1
{
class BankAccount
{
private int cust_id;
private string cust_name;
private int bal;
public BankAccount()
{
cust_id = 1000;
cust_name = "Not Yet Specified";
bal = 0;
}
public BankAccount(int cust_id, string cust_name, int bal)
{
this.cust_id = cust_id;
this.cust_name = cust_name;
this.bal = bal;
}
public BankAccount(BankAccount obj)
{
cust_id = obj.cust_id;
cust_name = obj.cust_name;
bal = obj.bal;
}
public void ShowData()
{
Console.WriteLine("cust id = {0}, customer name = {1}, Bank Balance = {2}", cust_id, cust_name, bal);
}
} 48
class Program { public static void Main(string[] args) { BankAccount a = new BankAccount(); // Invokes Default Constructor BankAccount b = new BankAccount(102, "Ben", 5000); // Invokes Parameterized Constructor BankAccount c = new BankAccount(b); // Invokes Copy Constructor a.ShowData(); b.ShowData(); c.ShowData(); } } }
11/6/2018
EEE-425 Programming Languages (2013) 9
49
A destructor method contains the actions you require when an instance of a class is destroyed
To explicitly declare a destructor method, use an identifier that consists of a tilde(~) followed by the class name
Destructors cannot receive parameters and therefore cannot be overloaded
A class can have at most one destructor
50
Employee class with destructor method
51
Destructor methods are automatically called when an object goes out of scope
You cannot explicitly call a destructor
The last object created is the first object destroyed
The base keyword can be used to access class members that are hidden by similarly named members of the current class
public class Shape { private int x, y; public override string ToString() { return "x=" + x + ",y=" + y; } }
internal class Circle : Shape { private int r; public override string ToString() { return base.ToString() + ",r=" + r; } }
using System; //The example II
namespace ConsoleApplication1
{
public class Owner
{
protected string ID = "2015513999";
protected string name = "Abdulcambaz Uzunkavakaltindayataruyumazoglu";
public virtual void Info()
{
Console.WriteLine("Name : {0}", name);
Console.WriteLine("ID : {0}", ID);
}
}
class Student : Owner
{
public string department = "EEM";
public override void Info()
{
base.Info(); // Calling the base class GetInfo method:
Console.WriteLine("Student Department: {0}", department);
}
}
class TestClass
{
public static void Main()
{
Student E = new Student();
E.Info();
Console.ReadLine(); }
}
}
53
using System; //The example I class BaseClass { public string Field1 = "In the base class"; } class DerivedClass : BaseClass { new public string Field1 = "In the derived class"; public void Display() { Console.WriteLine("{0}", Field1); // Access the derived class. Console.WriteLine("{0}", base.Field1); // Access the base class. } } class Program { static void Main() { DerivedClass oc = new DerivedClass(); oc.Display(); } }
The is operator is used to dynamically test if the run-time type of an object is compatible with a given type
private static void DoSomething(object o) { if (o is Car) ((Car)o).Drive(); }
11/6/2018
EEE-425 Programming Languages (2013) 10
The as operator tries to convert a variable to a specified type; if no such conversion is possible the result is null
More efficient than using is operator ◦ Can test and convert in one operation
private static void DoSomething(object o) { Car c = o as Car; if (c != null) c.Drive(); }
56
Components of a method
Class methods
◦ Parameters
Predefined methods
Value and nonvalue-returning methods
57
When you write programs in C#, you create two distinct type of classes
When you create a class, you create a class header and a class body
You declare the attributes and instance variables for a class within the curly braces using the same syntax you use to declare other variables
Declaring a class does not create any actual objects
After an object has been instantiated, its public methods can be accessed using the object’s identifier, a dot, and a method call
58
When you create a class that describes objects you will instantiate, and another class that instantiates those objects, you physically can contain both classes within the same file or place each class in its own file
Although there is no requirement to do so, most programmers place data fields in some logical order at the beginning of a class
Most programmers make class data fields private and class methods public
59
When you create an object, you provide storage for each of the object’s instance variables, but not for each instance method
A constructor method establishes an object
Like any other C# methods, constructors can be overloaded
A destructor method contains the actions you require when an instance of a class is destroyed
Questions?
11/6/2018
EEE-425 Programming Languages (2013) 11
homepage.divms.uiowa.edu
Prof. Roger Crawfis
http://www.cse.ohio-state.edu/~crawfis/cse459_CSharp/index.html
Programming C#, 4th Edition - Jesse Liberty – Chapt. 4
◦ Pls listen the podcast about the chapter 4 (Roger Crawfis)
◦ These slides are changed and modified
61
Write a game program that ◦ Create a class
◦ Takes a number from user,
◦ Compares this number with generated random value between two given positive numbers
◦ User tries maximum3 times then if user knows says «You Win» OR
You lost
Write a program as a calculator with (*, /, +, -, % ) operators by using methods ◦ Check the values that are not 0(zero) or none numeric
◦ Write the result on screen with variables and operator
62