Visual Programming COMP315 Chapter 3 Methods Classes Objects

Visual Programming COMP-315 Chapter #3 Methods, Classes, Objects & Inheritance

Classes/Methods • C# Framework Class Library (FCL) defines many classes, e. g. , • • • Console Message. Box Int 32 Math The definition of a class includes both methods and data properties: • methods, e. g. , • Console. Write( ) • Console. Write. Line( ) • Int 32. Parse( ) • properties, e. g. , • • Int 32. Min. Value Int 32. Max. Value Math. PI Math. E 2

Methods • A method should provide a well-defined, easy-to- understand functionality • A method takes input (parameters), performs some actions, and (sometime) returns a value • Example: invoking the Write. Line method of the Console class: Console. Write. Line ( "Whatever you are, be a good one. “ ); class method dot Information provided to the method (parameters) 3

Example: Math Class Methods 4

Methods Provide Abstraction and Reuse • An abstraction hides (or ignores) the right details at the right time • A method is abstract in that we don't really have to think about its internal details in order to use it • e. g. , we don't have to know how the Write. Line method works in order to invoke it • Why abstraction? • Divide and conquer • Reuse • Easier to understand 5

Method Declaration: Header • A method declaration begins with a method header class My. Class { … static int Square. Sum( int num 1, int num 2 ) parameter list method name The parameter list specifies the type and name of each parameter return type The name of a parameter in the method properties declaration is called a formal argument 6

Method Declaration: Body • The method header is followed by the method body class My. Class { … static int Square. Sum(int num 1, int num 2) { int sum = num 1 + num 2; return sum * sum; } … } 7

The return Statement • The return type of a method indicates the type of value that the method sends back to the calling location • A method that does not return a value has a void return type • The return statement specifies the value that will be returned • Its expression must conform to the return type 8

Calling a Method • Each time a method is called, the actual arguments in the invocation are copied into the formal arguments int num = Square. Sum (2, 3); static int Square. Sum (int num 1, int num 2) { int sum = num 1 + num 2; return sum * sum; } See Square. Sum. cs 9

Class Methods (a. k. a. Static Methods) • Previously we use class mainly to define related methods together: • For example all math related methods are defined in the Math class • The methods we have seen are defined as static (or class) methods • To make a method static, a programmer applies the static modifier to the method definition The result of each invocation of a class (static) method is completely determined by the actual parameters 10

A Quick Summary • If a method is a static method • Call the method by Class. Name. Method. Name(…); • If a method of a class is not a static method, then it is an instance method • • Create an object using the new operator Call methods of the object: object. Variable. Name. Method. Name(…); 11

Method Overloading: Signature • The compiler must be able to determine which version of the method is being invoked • This is by analyzing the parameters, which form the signature of a method • • The signature includes the method name, number, type, and order of the parameters The return type of the method is not part of the signature 12

Method Overloading Version 1 Version 2 double Try. Me (int x) { return x +. 375; } double Try. Me (int x, double y) { return x*y; } Invocation result = Try. Me (25, 4. 32) 13

Parameter Passing • If a modification on the formal argument has no effect on the actual argument, • it is call by value • If a modification on the formal argument can change the actual argument, • it is call by reference 14

Call-By-Value and Call-By-Reference in C# • Depend on the type of the formal argument • For the simple data types, it is call-by-value • Change to call-by-reference • The ref keyword and the out keyword change a parameter to call-by-reference • If a formal argument is modified in a method, the value is changed • The ref or out keyword is required in both method declaration and method call • ref requires that the parameter be initialized before enter a method while out requires that the parameter be set before return from a method 15

Example: ref static void Foo( int p ) {++p; } static void Main ( string[] args ) { int x = 8; Foo( x ); // a copy of x is made Console. Write. Line( x ); } static void Foo( ref int p ) {++p; } static void Main ( string[] args ) { int x = 8; Foo( ref x ); // x is ref Console. Write. Line( x ); } See Test. Ref. cs 16

Example: out static void Split( int time. Late, out int days, out int hours, out int minutes ) { days = time. Late / 10000; hours = (time. Late / 100) % 100; minutes = time. Late % 100; } static void Main ( string[] args ) { int d, h, m; Split( 12345, out d, out h, out m ); Console. Write. Line( “{0}d {1}h {2}m”, d, h, m ); } See Test. Out. cs 17

Variable Duration and Scope • Duration • Recall: a variable occupies some memory space • The amount of time a variable exists in memory is called its duration • Scope • The section of a program in which a variable can be accessed (also called visible) • A variable can have two types of scopes • Class scope • From when created in class • Until end of class (}) • Visible to all methods in that class • Block scope 18

• Scope • A local variable is accessible after it is declared and before the end of the block • A class variable is accessible in the whole class • Parameter passing with ref and out makes some variables aliases of others • Duration • A local variable may exist but is not accessible in a method, • e. g. , method A calls method B, then the local variables in method A exist but are not accessible in B. 19

Delegate A delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time. A delegate type maintains three important pieces of information : • The name of the method on which it make calls. • Any argument (if any) of this method. • The return value (if any) of this method. Defining a Delegate in C# when you want to create a delegate in C# you make use of delegate keyword. The name of your delegate can be whatever you desire. However, you must define the delegate to match the signature of the method it will point to. fo example the following delegate can point to any method taking two integers and returning an integer. public delegate int Delegate. Name(int x, int y); 20

A Delegate Usage Example namespace My. First. Delegate { //This delegate can point to any method, //taking two integers and returning an //integer. public delegate int My. Delegate(int x, int y); //This class contains methods that My. Delegate will point to. public class My. Class { public static int Add(int x, int y) { return x + y; } public static int Multiply(int x, int y) { return x * y; } } class Program { static void Main(string[] args) { //Create an Instance of My. Delegate //that points to My. Class. Add(). My. Delegate del 1 = new My. Delegate(My. Class. Add); //Invoke Add() method using the delegate. int add. Result = del 1(5, 5); Console. Write. Line("5 + 5 = {0}n", add. Result); //Create an Instance of My. Delegate //that points to My. Class. Multiply(). My. Delegate del 2 = new My. Delegate(My. Class. Multiply); //Invoke Multiply() method using the delegate. int multiply. Result = del 2(5, 5); Console. Write. Line("5 X 5 = {0}", multiply. Result); Console. Read. Line(); } } } 21

C# Classes • A C# class plays dual roles: • Program module: containing a list of (static) method declarations and (static) data fields • Blueprint for generating objects • It is the model or pattern from which objects are created • Supports two techniques which are essence of objectoriented programming – “data encapsulation” (for abstraction) – “inheritance” (for code reuse) 22

User-Defined Class • A user-defined class is also called a user-defined type • class written by a programmer • A class encapsulates (wrap together) data and methods: • data members (member variables or instance variables) • methods that manipulate data members 23

Objects • Class: a concept, e. g. , • the vehicle concept • Object • An instance of a concept, e. g. , the corolla at my home • An object has internal state • This is called encapsulation • Thus the action (method) may depend on both parameters and internal state. 24

Objects • An object has: • state - descriptive characteristics • behaviors - what it can do (or be done to it) • For example, consider a coin in a computer game • The state of the coin is its current face (head or tail) • The behavior of the coin is that it can be flipped • Note the interactions between state and behaviors • the behavior of an object might change its state • the behavior of an object might depend on its state 25

Creating and Accessing Objects • We use the new operator to create an object Random my. Random; my. Random = new Random(); This calls the Random constructor, which is a special method that sets up the object • Creating an object is called instantiation • An object is an instance of a particular class • To call a method on an object, we use the variable (not the class), e. g. , Random generator 1 = new Random(); int num = generate 1. Next(); 26

Example: the Random class Random methods Random () int Next () // returns an integer from 0 to Int 32. Max. Value int Next (int max) // returns an integer from 0 upto but not including max int Next (int min, int max) // returns an integer from min upto but not including max double Next. Double ( ) // returns a double number from 0 to 1 27

Data Declarations • You can define two types of variables in a class but not in any method (called class variables) • static class variables • nonstatic variables are called instance variables (fields) because each instance (object) of the class has its own copy • class variables can be accessed in all methods of the class • Comparison: Local variables • Variables declared within a method or within a block statement • Variables declared as local variables can only be accessed in the method or the block where they are declared 28

Method Declarations • • • Access methods : read or display data Predicate methods : test the truth of conditions Constructors • initialize objects of the class • they have the same name as the class – There may be more than one constructor per class (overloaded constructors) – Even if the constructor does not explicitly initialize a data member, all data members are initialized » primitive numeric types are set to 0 » boolean types are set to false » reference (class as type) types are set to null – If a class has no constructor, a default constructor is provided » It has no code and takes no parameters • they do not return any value – it has no return type, not even void • Can take argument 29

Accomplish Encapsulation: Access Modifiers • In C#, we accomplish encapsulation through the appropriate use of access modifiers • An access modifier is a C# keyword that specifies the accessibility of a method, data field, or class • Access modifiers are: public, private, protected & internal 30

The public and private Access Modifiers • Classes (types) and members of a class that are declared with public can be accessed from anywhere • Members of a type that are declared with private can only be accessed from inside the class • Members of a class declared without an access modifier have default private accessibility 31

The protected and internal Access Modifiers protected A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member. A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type. Accessibility: • • Cannot be accessed by object By derived classes Internal The internal keyword is an access modifier for types and type members. We can declare a class as internal or its member as internal. Internal members are accessible only within files in the same assembly (. dll). In other words, access is limited exclusively to classes defined within the current project assembly. Accessibility: In same assembly (public) • Can be accessed by objects of the class • Can be accessed by derived classes In other assembly (internal) • Cannot be accessed by object • Cannot be accessed by derived classes 32

Garbage Collection • When objects are no longer referenced, the C# Language Runtime (CLR) performs garbage collection • Garbage collection avoids running out of memory because unused memory has not been reclaimed • Allocation and deallocation of other resources (database connections, file access, etc. ) must be explicitly handled by programmers 33

Garbage Collection • You can use finalizers in conjunction with the garbage collector to release resources and memory • • Before garbage collector reclaims an object’s memory, it automatically calls the object’s finalizer Each class has only at most one finalizer (also called destructor) Name of a destructor is the ~ character, followed by the class name Destructors do not receive any arguments 34

static Class Members • Every object of a class has its own copy of all instance variables • Sometimes it is useful if all instances of a class share the same copy of a variable • Declare variables using keyword static to create only one copy of the variable at a time (shared by all objects of the type) • Static class members • static data • can be accessed in instance methods and static methods • invocation: Class. Name. Method. Name( … ); • can only access static data of the class See Employee. cs and Static. Test. cs 35

const and readonly Members • Declare constant members (members whose value will never change) using the keyword const • const members are implicitly static • const members must be initialized when they are declared • Use keyword readonly to declare members who will be initialized in the constructor but not change after that See Using. Const. And. Readonly. cs 36

Using the this reference • Every object can reference itself by using the keyword this • Often used to distinguish between a method’s variables and the instance variables of an object 37

Inheritance • Inheritance allows a software developer to derive a new class from an existing one • The existing class is called the parent class, or superclass, or base class • The derived class is called the child class, or subclass, or derived class. • As the name implies, the child inherits characteristics of the parent • That is, the child class inherits the methods and data defined for the parent class 38

Inheritance • Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class Animal # weight : int Animal Bird + Get. Weight() : int Bird Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent + Fly() : void 39

Examples: Base Classes and Derived Classes 40

Declaring a Derived Class • Define a new class Derived. Class which extends Base. Class class Base. Class { // class contents } class Derived. Class : Base. Class { // class contents } • Base class: the “parent” class; if omitted the parent is Object 41

Controlling Inheritance • A child class inherits the methods and data defined for the parent class; however, whether a data or method member of a parent class is accessible in the child class depends on the visibility modifier of a member • Variables and methods declared with private visibility are not accessible in the child class • Variables and methods declared with public visibility are accessible; but public variables violate our goal of encapsulation • Variables and methods declared with protected visibility in a parent class are only accessible by a child class or any class derived from that class 42

Calling Parent’s Constructor in a Child’s Constructor: the base Reference • Constructors are not inherited, even though they have public visibility • The first thing a derived class does is to call its base class’ constructor, either explicitly or implicitly • • implicitly it is the default constructor yet we often want to use a specific constructor of the parent to set up the "parent's part" of the object • Syntax: use base public Derived. Class : Base. Class { public Derived. Class(…) : base(…) { // … } } 43

Defining Methods in the Child Class: Overriding Methods • A child class can override the definition of an inherited method in favor of its own • That is, a child can redefine a method that it inherits from its parent • The new method must have the same signature as the parent's method, but can have different code in the body • The type of the object executing the method determines which version of the method is invoked 44

Overriding Methods: Syntax • override keyword is needed if a derived- class method overrides a base-class method • If a base class method is going to be overridden it should be declared virtual 45

Overloading vs. Overriding • Overloading deals with multiple methods in the same class with the same name but different signatures • Overloading lets you define a similar operation in different ways for different data • Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature • Overriding lets you define a similar operation in different ways for different object types 46

Single vs. Multiple Inheritance • Some languages, e. g. , C++, allow Multiple inheritance, which allows a class to be derived from two or more classes, inheriting the members of all parents • collisions, such as the same variable name in two parents, are hard to resolve • Thus, C# and Java support single inheritance, meaning that a derived class can have only one parent class 47

Class Hierarchies • A child class of one parent can be the parent of another child, forming a class hierarchy Animal Reptile Snake Lizard Bird Parrot Mammal Horse Bat 48

Another Example: Base Classes and Derived Classes Community. Memeber Employee Faculty Professor Student Staff Under Alumnus Graduate Instructor 49

The Object Class • All classes in C# are derived from the Object class • • • The Object class is therefore the ultimate root of all class hierarchies The Object class defines methods that will be shared by all objects in C#, e. g. , • • if a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class To. String: converts an object to a string representation Equals: checks if two objects are the same Get. Type: returns the type of a type of object A class can override a method defined in Object to have a different behavior, e. g. , • String class overrides the Equals method to compare the content of two strings 50

References and Inheritance • An object reference can refer to an object of its class, or to an object of any class derived from it by inheritance • For example, if the Holiday class is used to derive a child class called Christmas, then a Holiday reference can be used to point to a Christmas object Holiday Christmas Holiday day; day = new Holiday(); … day = new Christmas(); 51

References and Inheritance • Assigning an object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment Holiday = new Christmas(); • Assigning an ancestor object to a reference can also be done, but it is considered to be a narrowing conversion and must be done with a cast Christmas christ = new Christmas(); Holiday = christ; Christmas christ 2 = (Christmas)day; • The widening conversion is the most useful • for implementing polymorphism 52

Polymorphism via Inheritance • A polymorphic reference is one which can refer to different types of objects at different times • An object reference can refer to one object at one time, then it can be changed to refer to another object (related by inheritance) at another time • • it is the type of the object being referenced, not the reference type, that determines which method is invoked polymorphic references are therefore resolved at run-time, not during compilation; this is called dynamic binding • Careful use of polymorphic references can lead to elegant, robust software designs 53

Polymorphism via Inheritance • Suppose the Holiday class has a method called Celebrate, and the Christmas class redfines it • Now consider the following invocation: day. Celebrate(); • If day refers to a Holiday object, it invokes the Holiday version of Celebrate; if it refers to a Christmas object, it invokes the Christmas version 54

Abstract Class • Motivation: if you think no object of a class should be created, declare the class abstract • In general, an abstract class is a placeholder in a class hierarchy that represents a generic concept • The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate Vehicle Car Boat Plane 55

Abstract Classes: Syntax • Use the modifier abstract on a class header to declare an abstract class, e. g. , abstract class Vehicle { // … public abstract void Move(); } class Car : Vehicle { //… public void Move() { Console. Write. Line( “Car is moving!” ); } } abstract class Staff. Member { // … public abstract double Pay(); } 56

Abstract Class: Some Properties • An abstract class cannot be instantiated • but you can define a reference of an abstract class • Only abstract classes can contain abstract methods • The child of an abstract class must override the abstract methods of the parent, or it too must be declared abstract 57

C# Contains Many Other Features to Further Refine the Definition of a Class • Sealed class or method • if you declare a class or method sealed, then the class or method cannot be extended • Operator overloading • you can define operators for a class so that operations look more like a normal arithmetic operation 58

Using Interface for Multiple Inheritance • Java/C# decision: single inheritance, meaning that a derived class can have only one parent class • To take the advantages of multiple inheritance, Java/C# defines interfaces, which give us the best aspects of multiple inheritance without the complexity 59

C# Interface • A C# interface is a collection of methods, and properties • it can actually include other types of definitions • These methods and properties have no implementation • An interface is used to formally define a set of methods that a class will implement • An interface captures one aspect of a class • If class D is derived from class B, then you should feel comfortable in saying an object of D is also a B • If class D implements interface I, then you should feel comfortable in saying an object of D has I perspective 60

Interfaces: Syntax interface is a reserved word public interface IComplexity { int Level { get; set; } } public interface IDisplay. Able { void Paint(); } // inherits Question, implements two interfaces class Multi. Choice: Question, IComplexity, IDisplay. Able { public void Paint() {. . . } public int Level {. . . } public string Get. Question. Part() {} public string Get. Answer. Part() {} } 61

Interfaces • Methods in an interface have public visibility by default • An interface cannot be instantiated • A class implements an interface by • stating so in the class header after : • A class can implement multiple interfaces: the interfaces are separated by commas • If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will produce errors • A class that implements an interface can implement other methods as well 62

Polymorphism via Interfaces • An interface name can be used as the type of an object reference variable IDoable obj; • The obj reference can be used to point to any object of any class that implements the IDoable interface • The version of do. This that the following line invokes depends on the type of object that obj is referring to: obj. do. This(); 63

An Example ISpeak guest; guest = new Professor(); guest. Speak(); guest = Dog(); guest. Speak(); ISpeak special; special = new Professor(); special. Pontificate(); // compiler error ISpeak special; special = new Professor(); ((Professor)special). Pontificate(); public interface ISpeak { public void Speak(); } class Faculty {…} class Professor: Faculty, ISpeak { // public void Speak() {…} public void Pontificate() {…} } class Animal {} class Dog: Animal, ISpeak { // public void Speak() { … } } 64
- Slides: 64