Download presentation
Presentation is loading. Please wait.
1
Visual Programming COMP-315
Chapter #3 Methods, Classes, Objects & Inheritance
2
Classes/Methods C# Framework Class Library (FCL) defines many classes, e.g., Console MessageBox Int32 Math The definition of a class includes both methods and data properties: methods, e.g., Console.Write( ) Console.WriteLine( ) Int32.Parse( ) properties, e.g., Int32.MinValue Int32.MaxValue Math.PI Math.E
3
Console.WriteLine ( "Whatever you are, be a good one.“ );
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 WriteLine method of the Console class: Console.WriteLine ( "Whatever you are, be a good one.“ ); dot method class Information provided to the method (parameters)
4
Example: Math Class Methods
5
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 WriteLine method works in order to invoke it Why abstraction? Divide and conquer Reuse Easier to understand
6
Method Declaration: Header
A method declaration begins with a method header class MyClass { static int SquareSum( int num1, int num2 ) … parameter list method name The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument return type properties
7
Method Declaration: Body
The method header is followed by the method body static int SquareSum(int num1, int num2) { int sum = num1 + num2; return sum * sum; } class MyClass …
8
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
9
Calling a Method Each time a method is called, the actual arguments in the invocation are copied into the formal arguments int num = SquareSum (2, 3); static int SquareSum (int num1, int num2) { int sum = num1 + num2; return sum * sum; } See SquareSum.cs
10
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
11
A Quick Summary If a method is a static method
Call the method by ClassName.MethodName(…); 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: objectVariableName.MethodName(…);
12
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
13
Method Overloading double TryMe (int x) { return x + .375; } Version 1
double TryMe (int x, double y) { return x*y; } Version 2 result = TryMe (25, 4.32) Invocation
14
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
15
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
16
Example: ref See TestRef.cs static void Foo( int p ) {++p;}
static void Main ( string[] args ) { int x = 8; Foo( x ); // a copy of x is made Console.WriteLine( x ); } static void Foo( ref int p ) {++p;} static void Main ( string[] args ) { int x = 8; Foo( ref x ); // x is ref Console.WriteLine( x ); } See TestRef.cs
17
Example: out See TestOut.cs
static void Split( int timeLate, out int days, out int hours, out int minutes ) { days = timeLate / 10000; hours = (timeLate / 100) % 100; minutes = timeLate % 100; } static void Main ( string[] args ) { int d, h, m; Split( 12345, out d, out h, out m ); Console.WriteLine( “{0}d {1}h {2}m”, d, h, m ); } See TestOut.cs
18
Variable Duration and Scope
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
19
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.
20
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 DelegateName(int x, int y);
21
A Delegate Usage Example
namespace MyFirstDelegate { //This delegate can point to any method, //taking two integers and returning an //integer. public delegate int MyDelegate(int x, int y); //This class contains methods that MyDelegate will point to. public class MyClass { 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 MyDelegate //that points to MyClass.Add(). MyDelegate del1 = new MyDelegate(MyClass.Add); //Invoke Add() method using the delegate. int addResult = del1(5, 5); Console.WriteLine("5 + 5 = {0}\n", addResult); //Create an Instance of MyDelegate //that points to MyClass.Multiply(). MyDelegate del2 = new MyDelegate(MyClass.Multiply); //Invoke Multiply() method using the delegate. int multiplyResult = del2(5, 5); Console.WriteLine("5 X 5 = {0}", multiplyResult); Console.ReadLine(); } }
22
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 object-oriented programming “data encapsulation” (for abstraction) “inheritance” (for code reuse)
23
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
24
Objects Class: a concept, e.g., Object the vehicle concept
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.
25
Objects An object has: For example, consider a coin in a computer game
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
26
Creating and Accessing Objects
We use the new operator to create an object Random myRandom; myRandom = 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 generator1 = new Random(); int num = generate1.Next();
27
Example: the Random class
Random Random () Random methods int Next () // returns an integer from 0 to Int32.MaxValue 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 NextDouble ( ) // returns a double number from 0 to 1
28
Data Declarations Comparison: Local variables
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
29
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
30
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
31
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
32
The protected and internal Access Modifiers
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 derived classes
33
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
34
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
35
See Employee.cs and StaticTest.cs
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 static methods invocation: ClassName.MethodName( … ); can only access static data of the class See Employee.cs and StaticTest.cs
36
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 UsingConstAndReadonly.cs
37
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
38
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
39
Inheritance Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class Animal # weight : int + GetWeight() : int Bird + Fly() : void Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent Animal Bird
40
Examples: Base Classes and Derived Classes
41
Declaring a Derived Class
Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass Base class: the “parent” class; if omitted the parent is Object
42
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
43
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 DerivedClass : BaseClass { public DerivedClass(…) : base(…) { // … } }
44
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
45
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
46
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
47
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
48
Class Hierarchies A child class of one parent can be the parent of another child, forming a class hierarchy Animal Reptile Bird Mammal Snake Lizard Parrot Horse Bat
49
Another Example: Base Classes and Derived Classes
CommunityMemeber Employee Student Alumnus Faculty Staff Under Graduate Professor Instructor
50
The Object Class All classes in C# are derived from the Object class
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 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., ToString: converts an object to a string representation Equals: checks if two objects are the same GetType: 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
51
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 Holiday day; day = new Holiday(); … day = new Christmas(); Christmas
52
References and Inheritance
Assigning an object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment 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 The widening conversion is the most useful for implementing polymorphism Holiday day = new Christmas(); Christmas christ = new Christmas(); Holiday day = christ; Christmas christ2 = (Christmas)day;
53
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
54
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
55
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
56
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.WriteLine( “Car is moving!” ); } } abstract class StaffMember { // … public abstract double Pay(); }
57
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
58
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
59
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
60
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
61
interface is a reserved word
Interfaces: Syntax interface is a reserved word public interface IComplexity { int Level { get; set; } } public interface IDisplayAble { void Paint(); } // inherits Question, implements two interfaces class MultiChoice: Question, IComplexity, IDisplayAble { public void Paint() {...} public int Level {...} public string GetQuestionPart() {} public string GetAnswerPart() {} }
62
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
63
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 doThis that the following line invokes depends on the type of object that obj is referring to: obj.doThis();
64
An Example ISpeak guest; guest = new Professor(); guest.Speak();
guest = Dog(); 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() { … ISpeak special; special = new Professor(); special.Pontificate(); // compiler error ISpeak special; special = new Professor(); ((Professor)special).Pontificate();
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.