Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
Cukurova University Electrical-Electronics Eng. Dept.
9/19/2019
EEES-403 Programming Languages (2019) 1
Basic Object-Oriented Concepts in C Sharp
Basic Object-Oriented Concepts◦ Class
◦ Inheritance
◦ Polymorphism
◦ Constructor
◦ Destructors
Early high-level languages are typically called procedural languages.
Procedural languages are characterized by sequential sets of linear commands. The focus of such languages is on structure.
Examples include C, Fortran, HTML, VBScript
Most object-oriented languages are high-level languages.
The focus of OOP languages is not on structure, but on modeling data.
Programmers code using “blueprints” of data models called classes.
Examples of OOP languages include C++, Visual Basic.NET and Java.
int main(){int x,y,z;int a,b,c;
a=f1(x);b=f2(y);c=f3(z);…
}
int f1(){}
int f2()
{}
int f3(){}
Class A{Int x;Int f1();}
Class B{Int y;Int f2()}
Class C{Int z;Int f3();}
int main(){A a;B b;C c;
a.f1();b.f2();c.f3();…
}
procedural programming:
a sequence of ‘procedures’
Cukurova University Electrical-Electronics Eng. Dept.
9/19/2019
EEES-403 Programming Languages (2019) 2
Object – Unique programming entity that has methods, has attributes and can react to events.
Method – Things which an object can do; the “verbs” of objects. In code, usually can be identified by an “action” word -- Hide, Show
Attribute – Things which describe an object; the “adjectives” of objects. In code, usually can be identified by a “descriptive” word –Enabled, BackColor
Events – Forces external to an object to which that object can react. In code, usually attached to an event procedure
Class – Provides a way to create new objects based on a “meta-definition” of an object (Example: The automobile class)
Constructors – Special methods used to create new instances of a class (Example: A Honda Civic is an instance of the automobile class.)
Incorporation into a class of data & operations in one package
Data can only be accessed through that package
“Information Hiding”
Allows programmers to create new classes based on an existing class
Methods and attributes from the parent class are inherited by the newly-created class
New methods and attributes can be created in the new class, but don’t affect the parent class’s definition
Creating methods which describe the way to do some general function (Example: The “drive” method in the automobile class)
Polymorphic methods can adapt to specific types of objects.
Cukurova University Electrical-Electronics Eng. Dept.
9/19/2019
EEES-403 Programming Languages (2019) 3
A class is a data type that allows programmers
to create objects. A class provides a definition for an object, describing an object’s attributes (data) and methods (operations).
An object is an instance of a class. With one class, you can have as many objects as required.
This is analogous to a variable and a data type, the class is the data type and the object is the variable.
In old style programming, you had:◦ data, which was completely passive
◦ functions, which could manipulate any data
An object contains both data and methods that manipulate that data◦ An object is active, not passive; it does things
◦ An object is responsible for its own data
But: it can expose that data to other objects
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 Student might have◦ A grade (the internal state of the grade)
◦ An owner (some object representing a person)
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
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
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 onlyoperations permitted on its data
Example: a Student, with operations grade, takingclasses, GPA, etc.
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
Cukurova University Electrical-Electronics Eng. Dept.
9/19/2019
EEES-403 Programming Languages (2019) 4
class Temperature {
public:
double degree;
char scale;
};
a new (user-defined) type, a composite type: Temperature!
Two member variables: degree and scale
structure Temperature {
double degree;
char scale;
};
class Person {// Fields
{ private int Age; //Can get but not change
private string Name; // Cannot get or set// Methods
public void GetValues( int myAge, string myName)
{ Age = myAge; Name = myName; }public int DateOfBirth() { return 2019 - Age; } // getter
}
class Employee {// Fields
private String name; //Can get but not change
private double salary; // Cannot get or set// Constructor
Employee(String n, double s)
{name = n;
salary = s;
}// Methods
void pay () {
Console.WriteLine("Pay to the order of " + name + " $" + salary);}
public String getName() { return name; } // getter
}
class Person
{ private int Age;
private string Name;
public void GetValues( int myAge, string myName)
{ Age = myAge; Name = myName; }
public int DateOfBirth() { return 2019 - Age; }
}
.......
Person student; // declares student
student = new Person (); // allocates space
Person student = new Person(); // does both
But the student is still "blank" (null)
student.GetValues(20, "Ayse"); // Send a message
int year = student.DateOfBirth(); // sends a message
int Age; does two things:◦ It declares that Age is an integer variable◦ It allocates space to hold a value for Age
◦ For a primitive, this is all that is needed
Person student; also does two things◦ It declares that student is type Person◦ It allocates space to hold a reference to an Person
◦ For an object, this is not all that is needed
student = new Person ( );◦ This allocate space to hold a value for the Person◦ Until you do this, the Employee is null
temp1.degree=54.0;
temp1.scale=‘F’;
temp2.degree=104.5;
temp2.scale=‘C’;
Temperature temp1, temp2;
The modifier ‘public’ means that the member variables can be accessed from the objects
Cukurova University Electrical-Electronics Eng. Dept.
9/19/2019
EEES-403 Programming Languages (2019) 5
instance = object
field = instance variable
method = function
sending a message to an object = calling a function
These are all approximately true
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
A FileDialog is a Dialog is a Window is a Container
Container
Panel ScrollPane Window
Dialog Frame
FileDialog
Inheritance allows a software developer to derive a new class from an existing one.
The existing class is called the parent, super, or base class.
The derived class is called a child or subclass.
The child inherits characteristics of the parent.◦ Methods and data defined for the parent class.
The child has special rights to the parents methods and data.
The child has its own unique behaviors and data.
Inheritance relationships are often shown graphically in a classdiagram, with the arrow pointing to the parent class.
Inheritance should create an is-a relationship, meaning the child is amore specific version of the parent.
Animal
Bird
Base c lass Derived c lasses
Student GraduateStudent
UndergraduateStudent
Shape Circle
Triangle
Rectangle
Loan CarLoan
HomeImprovementLoan MortgageLoan
Employee FacultyMember StaffMember
Account CheckingAccount
SavingsAccount
Cukurova University Electrical-Electronics Eng. Dept.
9/19/2019
EEES-403 Programming Languages (2019) 6
Define a new class DerivedClass which extends BaseClass
class BaseClass
{
// class contents
}
class DerivedClass : BaseClass
{
// class contents
}
class CurrentAccount : BankAccount{
private int overdraftFacility;
public CurrentAccount(int n, string name, int b, int ov) : base(n, name, b) {
overdraftFacility = ov; }
public override void withdraw(int amount) {
if (base.Balance - amount > -overdraftFacility)base.Balance -= amount;
}}
class DepositAccount : BankAccount{
private float interestRate;
public DepositAccount(int n, string name, int b, float rate) : base( n, name,b) { interestRate = rate; }
float calcInterest() {
float interest = base.Balance * interestRate;base.Balance += (int)(interest);return interest;
} }
accountNumberaccountHolderbalance
deposit()withdraw()
overdraftFacility
withdraw()
interestRate
calcInterest()
accountNumberaccountHolderbalance
deposit()withdraw()
CurrentAccount DepositAccount
Polymorphism is the key concept in object oriented programming
Polymorphism literally means many forms
Essentially we are able to get many different types of object behaviour from a single reference type◦ This enables us to write easily extensible applications
For example in a computer game that simulates the movement of animals we can send ‘move’ commands to different types of animal
We send the commands via an animal reference which is the base class for the different animal types
◦ But each type behaves differently once it receives the command
◦ Such an approach leads to a readily extendable application
animal Move
Application
Cukurova University Electrical-Electronics Eng. Dept.
9/19/2019
EEES-403 Programming Languages (2019) 7
Polymorphism is implemented through references to objects
We can assign base class object references to any derived class object
BankAccount acc1 = new CurrentAccount(12345, "John Smith", 1000, 500);
BankAccount acc2 = new DepositAccount(54321, "Bill Jones", 2000, 5.0);
acc1
CurrentAccount
500
withdraw()
12345John Smith1000
deposit()withdraw()
acc2
DepositAccount
5.0
calcInterest()
54321Bill Jones2000
deposit()withdraw()
We can see that in the case of the reference to a CurrentAccountObject object, method withdraw() is overidden in the derived class
The question is, which one is called at runtime?
public class BankAccountTest{
static void Main(string[] args){
BankAccount acc1 = new CurrentAccount(12345, "John Smith“,1000, 500);
acc1.withdraw(250); // Which withdraw()?}
}
accountNumberaccountHolderbalance
deposit()withdraw()
overdraftFacility
withdraw()
acc1
CurrentAccount
Which one
is called?
Instance constructors are special methods that are called when a class or struct is instantiated
Performs custom initialization Can be overloaded
If a class doesn’t define any constructors, an implicit parameterless constructor is created
Cannot create a parameterless constructor for a struct◦ All fields initialized to zero/null
Cukurova University Electrical-Electronics Eng. Dept.
9/19/2019
EEES-403 Programming Languages (2019) 8
class addition{
int a, b;public addition() //default contructor{
a = 100;b = 175;
}
public static void Main(){
addition obj = new addition(); //an object is created , constructor is called
Console.WriteLine(obj.a);Console.WriteLine(obj.b);Console.Read();
}}
One constructor can call another with a constructor initializer
Use the this keyword. The called constructor will execute before the body of the current constructor.
class employee
{private string name;
private int age;public employee(employeeemp) // declaring Copy constructor.
{name = emp.name;
age = emp.age;}
public employee(stringname, int age) // Instance constructor.{
this.name = name;this.age = age;
}public string Details // Get deatils of employee
{return " The age of " + name +" is "+ age.ToString();
}}
45
A destructor is a method that is called before an instance is garbage collected
Used to clean up any resources held by the instance, do bookkeeping, etc.
Only classes, not structs can have destructors
class Program{
~Program() // destructor define {
// clean up statement}
}
C# destructors are non-deterministic
They are not guaranteed to be called at a specific time
They are guaranteed to be called before shutdown
You can not directly call the destructor
Slows down the garbage collection if you define one, so don’t unless you have to.
Cukurova University Electrical-Electronics Eng. Dept.
9/19/2019
EEES-403 Programming Languages (2019) 9