Chapter three Object-Oriented Fundamentals in C#.NET
1 Prepared by Tesfa K. 5/14/2022
Object Oriented Concepts(Class and objects) In an attempt to manage the ever-increasing size of the programs, structured programming was introduced to break down the code into manageable segments called functions or procedures. This was an improvement, but as programs performed more complex business functionality and interact with other systems, the following drawbacks of structural programming was observed: Programs became harder to maintain. Existing functionality was hard to modify (which affects all the system’s functionalities) New programs were essentially built from scratch (i.e. Because there is no way to reuse previous efforts) The main advantages of OOP are to make complex software faster to develop and easier to maintain. OOP enables the easy reuse of code by applying simple and widely accepted rules (principles). As a result, many business software developers turned to object-oriented methods and programming languages.
2 Prepared by Tesfa K. 5/14/2022
Object-Oriented Concepts… The benefits of Object-Oriented Programming:- The ability to maintain and implement changes in the programs more efficiently and rapidly. The ability to create software systems more effectively using a team process, allowing specialists to work on parts of the system. The ability to reuse code components in other programs and purchase components written by third-party developers to increase the functionality of existing programs with little effort. Better integration with loosely coupled distributed-computing systems. Improved integration with modern operating systems. The ability to create a more attractive graphical-user interface for the users.
3 Prepared by Tesfa K. 5/14/2022
Object-Oriented Concepts… Some features of Object Oriented programming are as follows: Emphasis on data rather than procedure Programs are divided into Objects Data is hidden and cannot be accessed by external functions Objects can communicate with each other through functions New data and functions can be easily added whenever necessary Follows bottom-up approach Concepts of OOP: Objects Classes Data Abstraction and Encapsulation Inheritance Polymorphism
4 Prepared by Tesfa K. 5/14/2022
Object An object is a structure that incorporate a set of data items (fields) with operations (methods ) to manipulate them. Object combines data and operations in one place. A circle object, for example, has a data field radius, which is the property that characterizes a circle. The state of an object (also known as its properties or attributes) is represented by data fields with their current values. The behavior of an object (also known as its actions) is defined by methods. Example: dogs have states (name, color, hungry, breed) and behaviors (bark, fetch, and wag tail). Method is an action performed by an object To invoke a method within an object is to ask the object to perform an action. For example, you may define a method named getArea() for circle objects. A circle object may invoke getArea() to return its area. objects interact and communicate with each other by sending messages to each other.
5 Prepared by Tesfa K. 5/14/2022
Class A class is a template or blueprint that defines what an object’s data fields and methods will be. (a blueprint of a specific object.) Class is a collection of objects of similar type. Classes are user-defined data types & behave like the built-in types of programming language. A class defines the kinds of data and the functionality their objects will have. An object is an instance of a class. E.g Ibsa is an instance of a Student You can create many instances of a class. Creating an instance is referred to as instantiation. The terms object and instance are often used interchangeable.
6 Prepared by Tesfa K. 5/14/2022
Class… The syntax for a simple class declaration is modifiers class class-name { body } access modifiers define the accessibility of the class and its members. Public, private, protected, and internal are access modifiers in C#. The Public modifier allows any part of the program in the same assembly or another assembly to access the class and its members. The Private modifier restricts other parts of the program from accessing the class and its members. The Internal modifier allows other program code in the same assembly to access the class or its members. This is default access modifiers if no modifier is specified. The Protected modifier allows codes in the same class or a class that derives from that class to access the class or its members. Body is a sequence of declarations of variables, constructors, and methods
7 Prepared by Tesfa K. 5/14/2022
Object-Oriented Concepts… Following is the example of creating objects in the c# programming language
using System; public class Users
namespace Try { { public Users(string name, int age) class Program { { static void Main(string[] args) Name = name; Age = age; { } Users user = new Users(“ash Dasari", 30); public void GetUserDetails() user.GetUserDetails(); { Console.WriteLine("Name: {0}, Age: {1}", Name, Age); Console.WriteLine("PressKey to Exit.."); } Console.ReadLine(); } }} }
8 Prepared by Tesfa K. 5/14/2022
Object-Oriented Concepts… In order for a programming language to be object-oriented, it has to enable working with classes and objects as well as the implementation and use of the fundamental object-oriented principles and concepts: Inheritance, Abstraction, Encapsulation and Polymorphism.
9 Prepared by Tesfa K. 5/14/2022
Inheritance Inheritance is the process by which one object acquires the properties of another object. A class derives from a base class, taking all the base class members fields and functions. Inheritance is most useful when you need to add functionality to an existing type. The syntax of inheritance; Class derivedClass : baseClass { body }
10 Prepared by Tesfa K. 5/14/2022
Inheritance… 1. using System; 16. class Inheritance 2. namespace oops 17. { 3. { 18. static void Main(string[] args) 19. { 4. public class Father 5. { 20. Father fObj = new Father(); 21. fObj.FatherMethod(); 6. public void FatherMethod() 22. Child cObj = new Child(); 7. { 23. cObj.FatherMethod(); 8. Console.WriteLine("this property belong to Father"); 24. cObj.ChildMethod(); 25. } 9. }} 26. } 10. public class Child : Father 11. { 12. public void ChildMethod() 13. { 14. Console.WriteLine("this property belong to Child"); 15. }}}
11 Prepared by Tesfa K. 5/14/2022
What is Encapsulation in C#? The process of binding the data and functions together into a single unit (i.e. class) is called encapsulation in C#. The process of defining a class by hiding its internal data members from outside the class and accessing those internal data members only through publicly exposed methods (setter and getter methods) is called encapsulation. Data encapsulation is also called data/information hiding because we can hide the internal data from outside the class. A Secretary using a Laptop only knows about its screen, keyboard and mouse. Everything else is hidden internally under the cover. She does not know about the inner workings of Laptop, because she doesn’t need to, and if she does, she might make a mess. Therefore parts of the properties and methods remain hidden to her.
12 Prepared by Tesfa K. 5/14/2022
How can we implement Encapsulation in C#? In C# Encapsulation is implemented By declaring the variables as private (to restrict its direct access from outside the class) By defining one pair of public setter and getter methods to access private variables. We declare variables as private to stop accessing them directly from outside the class. The public setter and getter methods are used to access the private variables from outside the class. By implementing encapsulation in c#, we are protecting or securing the data.
13 Prepared by Tesfa K. 5/14/2022
Encapsulation in C# using Accessors and Mutators:
1. namespace EncapsulationDemo 16. class BankUser
2. { 17. { 3. public class Bank 18. public static void Main() 4. { 19. { 5. private double balance; 20. Bank SBI = new Bank(); 6. //creating public setter and getter methods 21. SBI.setBalance(500); 7. public double getBalance() 22. Console.WriteLine(SBI.getBalance()); 8. { 23. Console.WriteLine("Press any key to exist."); 9. return balance; 24. Console.ReadKey(); 10. } 25. } 11. public void setBalance(double balance) 26. } 12. { 27. } 13. this.balance = balance; 14. } 15. }
14 Prepared by Tesfa K. 5/14/2022
C# Polymorphism Polymorphism is a Greek word, meaning "one name many forms".
Polymorphism provides the ability to a class to have multiple
implementations with the same name. There are two types of polymorphism in C#:- 1. Compile time polymorphism 2. Runtime polymorphism Compile time polymorphism is achieved by method overloading and operator overloading in C#. It is also known as static binding or early binding because the decision of which method is to be called is made at compile time. In method overloading, the method / function has a same name but different signatures. 15 Prepared by Tesfa K. 5/14/2022 Example of Compile Time Polymorphism 1. public class TestData 12. class Program 2. { 13. { 3. public int Add(int a, int b, int c) 14. static void Main(string[] args) 4. { 15. { 5. return a + b + c; 16. TestData dataClass = new TestData(); 6. } 7. public int Add(int a, int b) 17. int add2 = dataClass.Add(45, 34, 67); 8. { 18. int add1 = dataClass.Add(23, 34); 9. return a + b; 19. } 10. } 20. } 11. }
16 Prepared by Tesfa K. 5/14/2022
Dynamic / Runtime Polymorphism Dynamic / runtime polymorphism is also known as late binding. Here, the method name and the method signature (number of parameters and parameter type) must be the same and may have a different implementation. Method overriding is an example of dynamic polymorphism. Method overriding can be done using inheritance. With method overriding it is possible for the base class and derived class to have the same method name and method signature. The compiler will decide which method to call at runtime. For example, think of a base class called Animal that has a method called animalSound(). Derived classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):
17 Prepared by Tesfa K. 5/14/2022
Example of Runtime Polymorphism 1. class Animal // Base class (parent) 2. { 3. public virtual void animalSound() 15. class Dog : Animal // Derived class (child) 16. { 4. { 17. public override void animalSound() 5. Console.WriteLine("The animal’s sound"); 18. { 19. Console.WriteLine("The dog says: bow wow"); 6. } 20. } 7. } 21. } 8. class Pig : Animal//Derived class (child) 22. class Program 23. { 9. { 24. static void Main(string[] args) 10. public override void animalSound() 25. { 26. Animal myAnimal = new Animal();//Create Anml obj 11. { 27. Animal myPig = new Pig(); // Create a Pig object 12. Console.WriteLine("The pig says: wee wee"); 28. Animal myDog = new Dog(); // Create a Dog object 13. } 29. myAnimal.animalSound(); 30. myPig.animalSound(); 14. } 31. myDog.animalSound(); 32. } 33. }
18 Prepared by Tesfa K. 5/14/2022
Abstract Classes and Methods Data abstraction is the process of hiding certain details and showing only essential information to the user. Abstraction can be achieved with either abstract classes or interfaces. The abstract keyword is used for classes and methods: Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited by another class). Abstract method: can only be used in an abstract class, and it does not have a body. The body of abstract method is provided by the derived class. An abstract class can have both abstract and regular methods.
19 Prepared by Tesfa K. 5/14/2022
Abstract Classes and Methods… abstract class Animal { public abstract void animalSound(); public void sleep() { Console.WriteLine("Zzz"); }} From the example above, it is not possible to create an object of the Animal class: Animal myObj = new Animal(); // Will generate an error To access the abstract class, it must be inherited from another class.
20 Prepared by Tesfa K. 5/14/2022
Abstract Classes and Methods… 1. using System; 2. public abstract class Shape 3. { 4. public abstract void draw(); 5. } 6. public class Rectangle : Shape 7. { 20. public class TestAbstract 8. public override void draw() 21. { 9. { 22. public static void Main() 10. Console.WriteLine("drawing rectangle..."); 23. { 11. } 12. } 24. Rectangle r = new Rectangle(); 13. public class Circle : Shape 25. r.draw(); 14. { 26. Circle c = new Circle(); 15. public override void draw() 27. c.draw(); 16. { 28. } 17. Console.WriteLine("drawing circle..."); 29. } 18. } 19. }
21 Prepared by Tesfa K. 5/14/2022
Interface An interface is a completely "abstract class", which can only contain abstract methods with empty bodies Example interface Animal { void animalSound(); // interface method (does not have a body) void run(); } By default, members of an interface are abstract and public. Interfaces can contain methods, but not fields. To access the interface methods, the interface must be "implemented" by another class. To implement an interface, use the : symbol (just like with inheritance). The body of the interface method is provided by the "implement" class. Note that you do not have to use the override keyword when implementing an interface: 22 Prepared by Tesfa K. 5/14/2022 Interface… 1. using System; 18. { 2. public interface Drawable { 19. public static void Main() 3. void draw(); 20. { 4. } 21. Drawable d; 5. public class Rectangle : Drawable { 22. d = new Rectangle(); 6. public void draw() 23. d.draw(); 7. { 24. d = new Circle(); 8. Console.WriteLine("drawing rectangle..."); 25. d.draw(); 9. } 26. } 10. } 27. } 11. public class Circle : Drawable { 12. public void draw() 13. { 14. Console.WriteLine("drawing circle..."); 15. } 16. } 17. public class TestInterface