1 / 46

Section 5 – Classes

Section 5 – Classes. Object-Oriented Language Features. Abstraction Abstract or identify the objects involved in the problem Encapsulation Packaging data and behaviour into a single unit - the class Inheritance Reuse of code through extending program units Polymorphism

khan
Download Presentation

Section 5 – Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Section 5 – Classes

  2. Object-Oriented Language Features • Abstraction • Abstract or identify the objects involved in the problem • Encapsulation • Packaging data and behaviour into a single unit - the class • Inheritance • Reuse of code through extending program units • Polymorphism • Multiple implementations of the same behaviour

  3. Classes in C# • Classes model real-world objects and define • Attributes (state, properties, fields) • Behaviour (methods, operations) • Classes describe the structure of objects • Objects describe particular instance of a class • Properties hold information about the modeled object relevant to the problem • Operations implement object behaviour

  4. Classes Classes are declared by using the keyword class followed by the class name and a set of class members surrounded by curly braces { }. using System; public class House { ... } public class Program { public static void Main() { int bedrooms = 3; // assuming bedrooms defined in House } }

  5. Basic syntax for class declaration Class comprises a class header and class body. public class class_name { class body } Note: No semicolon (;) to terminate class block. But statements must be terminated with a semicolon ; Class body comprises class members – constructor, data fields and methods.

  6. In C#, individual classes and class members need to be prefixed with visibility modifiers. By default, if you declare a member variable (or anything else) in a class but do not specify its access level, the member is considered private and cannot be accessed from outside, i.e. by a non-member of that class. Therefore, to make a member accessible by other classes, you must declare it as public. You can use a mix of public and private members in a class and there is no rule on which access level should be listed first or last.

  7. C# - Basics: Classes • Declaration • public Class MyClass{...} • Constructors • publicMyClass(parameters) {...} • newoperator – create an instance of the class • MyClassobjMyClass = newMyClass();

  8. Variables of a class type are created with the new operator using System; public class House { ... } public class Program { public static void Main() { House MyHouse= new House(); // create object } }

  9. Classes in C# can have members: • Data fields, methods, properties, indexers, events, operators, constructors, destructors, … • Inner classes • Members can have access modifiers • public, private, … • Members can be • static (common) or specific for a given object

  10. Class Definition and Members • Class definition consists of • Class declaration • Data Fields • Constructors • Properties • Methods

  11. Contents of Classes class class_name{ ... data fields, constants... ... methods... ... constructors... ... properties... ... derived classes... }

  12. Every class has a constructor, which is called automatically any time an instance of a class is created. • The purpose of constructors is to initialize class members when the class is created. • Constructors do not have return values and always have the same name as the class. • Classes can have multiple constructors, as long as the parameter list is different for each constructor. • The constructor with no parameters is known as the default constructor. • If a class does not define any constructors, an implicit parameterless constructor is created.

  13. Calling the constructor ClassNameobjectName = new ClassName(argumentList); Or ClassNameobjectName; objectName = new ClassName(argumentList);

  14. public class Person { private string name; private int age; // Parameterless constructor public Person() { name = null; age = 0; } // Constructor with parameters public Person(string name, int age) { this.name = name; this.age = age; } // More code ... } As rule constructors should initialize all class fields.

  15. using System; class OutputClass { private string myString; // Constructor public OutputClass(string inputString) { myString = inputString; } public void printString() { Console.WriteLine(myString); } } Continued …

  16. // Program start class class ExampleClass { // Main begins program execution. public static void Main() { // Instance of OutputClass OutputClassoutCl = new OutputClass("This is printed by the output class."); // Call OutputClass method outCl.printString(); } }

  17. To create an instance (i.e. object) of a class, use the new operator which invokes the class constructor. newclass_name(parameters) Variables of type class_name can be created in this way: class_nameobject_name = newclass_name(params); The dot operator (.) is used in conjunction with the object to access the members (properties and methods) of a class (like C++ and Java).

  18. Access Modifiers • Class members can have access modifiers • Used to restrict the classes (i.e. clients) able to access them • Supports the OOP principle "encapsulation“ • Class members can be: • public – accessible from any class • private – accessible from the class itself only There are others!

  19. Accessor and Mutator Examples publicdoubleGetNoOfSquareMeters( ) { returnnoOfSquareMeters; } publicvoidSetNoOfSquareMeters(doublesquareMeters) { noOfSquareMeters = squareMeters; } Accessor Mutator

  20. Property • A new feature for C# - another way of implementing accessor and mutator methods. • Properties look like a data field • But more closely aligned to methods • Standard naming convention in C# for properties • Use the same name as the instance variable or field, but start with uppercase character

  21. The Role of Properties • Expose object's data to the outside world • Control how the data is manipulated • Ensure the internal object state is correct • E.g. price should always be kept positive • Properties can be: • Read-only • Write-only • Read and write

  22. Defining Properties • Properties work as a pair of methods • Getter and setter • Properties should have • Access modifier (public) • Return type • Unique name • Get and / or Set part • Can contain code processing data in specific way, e.g. apply validation

  23. Defining Properties – Example • public class Point • { • private int xCoord; • private int yCoord; • public int XCoord • { • get { return xCoord; } • set { xCoord = value; } • } • public int YCoord • { • get { return yCoord; } • set { yCoord = value; } • } • // More code ... • }

  24. class MyClass { private string message ; public string Message { get { return message; } set { message = value; } } } class Program { static void Main() { // create instance of MyClass MyClass greetings = new MyClass(); greetings.Message = "Hello World!"; string answer = greetings.Message; Console.WriteLine("{0}", answer); Console.ReadLine(); } }

  25. Dynamic Properties • Properties are not bound to a class field – they can be used calculate a value dynamically • public class Rectangle • { • private double width; • private double height; • // More code ... • public double Area • { • get • { • return width * height; • } • } • }

  26. How to Use Classes • Create an instance • Initialize its fields • Manipulate the instance • Read / modify properties • Invoke methods

  27. Example - Define Class for a Dog • Define a simple class that represents information about a dog • The dog should have name and breed • If there is no name or breed assigned to the dog • It should be named “Fido" • Its breed should be “Mongrel" • It should be able to view and change the name and the breed of the dog • The dog should be able to bark

  28. To define a simple class that represents information about a dog • The dog should have name and breed →data fields – string type • If there is no name and breed assigned to the dog • It should be named “Fido" • Its breed should be “Mongrel" → constructors • It should be able to view and change the name and the breed of the dog → get and set methods • The dog should be able to bark → method

  29. public class Dog{ private string name; private string breed; public Dog() // Constructors { name = “Fido"; breed = “Mongrel"; } public Dog(string dogName, string dogBreed) { name = dogName; breed = dogBreed; }

  30. public string Name // get and set properties { get { return name; } set { name = value; } } public string Breed // get and set properties { get { return breed; } set { breed = value; } } public void Bark() { Console.WriteLine("{0} said: Woof!", name); } }

  31. Example • Task is as follows: • Create 3 dogs • Put all dogs in an array • Iterate through the array elements and ask each dog to bark • Note: • Use the Dog class from the previous example

  32. public class Doggies static void Main() { // Use the Dog constructor to set name and breed Dog firstDog = new Dog(); // default Dog secondDog = new Dog(“Fritz”, “German Shepherd”); Dog thirdDog = new Dog(“Tommy”, “Bulldog”); • // Save the dogs in an array • Dog[] dogs = new Dog[] {firstDog, secondDog, thirdDog }; • // Ask each of the dogs to bark • foreach(Dog dog in dogs) • { • dog.Bark(); • } • } • }

  33. Inheritance • Enables you to • Create a general class and then define specialized classes that have access to the members of the general class • Associated with an "is a" relationship • Specialized class “is a” form of the general class A derived (or child) class inherits from a base (or parent) class The derived class inherits all the attributes and behaviour of the base class. The derived class may implement also its own attributes and behavior. The derived class may override inherited attributes and behaviour

  34. Inheritance hierarchy for Shapes.

  35. Extending Classes • Use a single colon • Between the derived class name and its base class name • Inheritance works only in one direction • A child inherits from a parent public class ChildClass : ParentClass { ... }

  36. Child class may implement its own constructors, attributes and methods in addition to those inherited from the parent class. • Instantiating an object of a derived class • - Calls the constructor for both the base class and the derived class • - The base class constructor willexecute first • Any derived class inherits all the data and methods of its base class • - Including private data and methods • - Cannot use or modify private data and methods directly

  37. using System; public class ParentClass { public ParentClass() { Console.WriteLine("Parent Constructor."); } public void print() { Console.WriteLine("I'm a Parent Class."); } } public class ChildClass : ParentClass { public ChildClass() { Console.WriteLine("Child Constructor."); } public static void Main() { ChildClass child = new ChildClass(); child.print(); } } Child class object invokes print() inherited from parent class.

  38. Creating Base Classes for Inheritance • Can define your own classes from which other classes can inherit • Base class is also called the super or parent class • Data members are defined with a private access modifier • Constructors are defined with public access modifiers • Properties offer public access to data fields

  39. Overriding Base Class Methods • Derived class contains data and methods defined in the original class • Polymorphism • Using the same method or property name to indicate different implementations • Derived class can override and hide methods and data from the base class

  40. public class Animal { public void Greet() { Console.WriteLine("Hello, I'm some sort of animal!"); } } public class Dog : Animal { } This example defines an Animal class, with a simple method to output a greeting. Then a derived Dog class is defined - the Dog class inherits from the Animal class.

  41. Animal myAnimal= new Animal(); myAnimal.Greet(); Dog myDog= new Dog(); myDog.Greet(); // use parent class method Even though we have not defined a Greet() method for the Dog class, it still knows how to greet us, because it inherits this method from the Animal class. May also define a Greet() method in the Dog class … that overrides the one in the parent class.

  42. public class Animal { public virtual void Greet() { Console.WriteLine("Hello, I'm some sort of animal!"); } } public class Dog : Animal { public override void Greet() { Console.WriteLine("Hello, I'm a dog!"); } } Besides the added method on the Dog class, you should notice two things: I have added the virtual keyword to the method in the Animal class, and on the method in the Dog class, I use the override keyword. In C#, you are not allowed to override a member of a class unless it is marked as virtual.

  43. If you want to, you can still access the inherited method, even when you override it, using the base keyword. public override void Greet() { base.Greet(); Console.WriteLine("Yes I am - a dog!"); } Inheritance is not only from one class to another - you can have a whole hierarchy of classes, which inherits from each other. - For instance, we could create a Puppy class, which inherits from our Dog class, which in turn inherits from the Animal class. What you cannot do in C#, is to let one class inherit from several other classes at the same time. - Multiple inheritance, as it is called, is not supported by C#.

  44. Accessing Base Class Methods from a Derived Class • Use the keyword base to access the parent class method

  45. Overriding Methods • Replace the method defined at a higher level • Keyword override included in derived class • Base method includes virtual, abstract, or override keyword • Overriding differs from overloading a method • Overridden methods have exactly the same signature • Overloaded methods each have a different signature

  46. Overriding Methods (continued) • Example of polymorphism • ToString( ) method can have many different definitions • ToString( ) uses the virtual modifier, implying that any class can override it • Derived classes inherit from a base class • Also called subclasses or child classes • Protected access modifiers • Access only to classes that derived from them • Access to change data in the base class

More Related