0% found this document useful (0 votes)
5 views

Session 3

Uploaded by

alexteyeametepey
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Session 3

Uploaded by

alexteyeametepey
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

DCIT 318

PROGRAMMING II

Session 3 – OOP using C# Part II

Lecturer: Mr. Paul Ammah, CSD


Contact Information: [email protected]

Department of Computer Science


School of Physical and Mathematical Sciences
2022/2023
Inheritance in C# and .NET
• Inheritance is one of the fundamental attributes of object-
oriented programming.
• It allows you to define a child class that reuses (inherits),
extends, or modifies the behavior of a parent class.
• Not all members of a base class are inherited by derived
classes.
• The following members are not inherited:
• Static constructors, which initialize the static data of a class.
• Instance constructors, which you call to create a new instance of
the class. Each class must define its own constructors.
• Finalizers, which are called by the runtime's garbage collector to
destroy instances of a class.
Slide 2
Inheritance in C# and .NET
• A member's accessibility affects its visibility for
derived classes as follows:
– Private members are visible only in derived classes that
are nested in their base class.
– Protected members are visible only in derived classes.
– Internal members are visible only in derived classes that
are located in the same assembly as the base class.
• They are not visible in derived classes located in a different
assembly from the base class.
– Public members are visible in derived classes and are part
of the derived class' public interface.
Slide 3
Inheritance in Action
public class A
{ public class Example
public void Method1() {
{ public static void Main(){
// Method implementation. B b = new ();
} b.Method1();
} }
}
public class B : A { }

Slide 4
Inheritance in Action
public class A
{ public class AccessExample
private int _value = 10;
{
public static void Main(string[] args)
public class B : A
{ {
public int GetValue() var b = new A.B();
{ Console.WriteLine(b.GetValue());
return _value; }
} }
}
}

public class C : A
{
// public int GetValue()
// {
// return _value;
// }
}

Note: Accessing GetValue() from class C is not possible


Slide 5
from class B
Overriding Inherited Members
• Derived classes can also override inherited members
by providing an alternate implementation
• In order to be able to override a member, the
member in the base class must be marked with the
virtual keyword
• By default, base class members are not marked as
virtual and cannot be overridden

Slide 6
Overriding Inherited Members
public class A
{
public virtual void Method1()
{
// Do something.
}
}

public class B : A
{
public override void Method1() {
// Do something else.
}
}
Slide 7
override Modifier
• The override modifier is required to extend or
modify the abstract or virtual implementation of an
inherited method, property, indexer, or event.

Slide 8
override Modifier
abstract class Shape
{
public abstract int GetArea();
}

class Square : Shape


{
private int _side;

public Square(int n) => _side = n;

public override int GetArea() => _side * _side;


}

Slide 9
Override Example
public class Employee
{
public string Name { get; }

protected decimal _basepay;

public Employee(string name, decimal basepay)


{
Name = name;
_basepay = basepay;
}

// Declared virtual so it can be overridden.


public virtual decimal CalculatePay()
{
return _basepay;
}
}

Slide 10
Override Example contd.
public class SalesEmployee : Employee
{
private decimal _salesbonus;

public SalesEmployee(string name, decimal basepay,


decimal salesbonus)
: base(name, basepay)
{
_salesbonus = salesbonus;
}

// Override the CalculatePay method


public override decimal CalculatePay()
{
return _basepay + _salesbonus;
}
Slide 11
}
Implicit inheritance
• Besides any types that they may inherit from through
single inheritance, all types in the .NET type system
implicitly inherit from Object or a type derived from
it.

• Inheritance applies only to classes and interfaces.


– Other type categories (structs, delegates, and enums) do
not support inheritance.

Slide 12
Abstract Classes and Class Members
• The abstract keyword enables you to create classes
and class members that are incomplete and must be
implemented in a derived class.

public abstract class A


{
public abstract void DoWork(int i);
}

Slide 13
Interfaces
• An interface defines a contract.
• A class or struct that implements an interface shall
adhere to its contract.
• An interface may inherit from multiple base
interfaces, and a class or struct may implement
multiple interfaces.

Slide 14
Interfaces
interface ISampleInterface
{
void SampleMethod();
}

class ImplementationClass : ISampleInterface


{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{
// Method implementation.
}

}
Slide 15
Interfaces
public interface INamed
{
public string Name {get; set;}
}
• An interface may include
– Constants
– Static fields, methods, properties, indexers, and events
– Operators
– Nested Types
– Explicit access modifiers (default is public)
Slide 16
Interfaces
interface ISampleInterface
{
void SampleMethod();
}

class ImplementationClass : ISampleInterface


{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{
// Method implementation.
}

}
Slide 17
Interface Inheritance
public interface IControl
{
void Paint();
}
public interface ISurface
{
void Draw();
}
public class SampleClass : IControl, ISurface
{
public void Paint()
{
Console.WriteLine("Paint method in SampleClass");
}

public void Draw()


{
Console.WriteLine(”Draw method in SampleClass");
}
}

Slide 18
Interface Inheritance
public interface IControl
{
void Paint();
}
public interface ISurface
{
void Paint();
}
public class SampleClass : IControl, ISurface
{
public void IControl.Paint()
{
Console.WriteLine("Paint method from IControl");
}

public void ISurface.Paint()


{
Console.WriteLine(”Paint method from ISurface");
}
}

Slide 19
Operator Overloading
• A user-defined type can overload a predefined C#
operator
• Use the operator keyword to declare an operator.
• An operator declaration must satisfy the following
rules:
– It includes both a public and a static modifier.
– A unary operator has one input parameter.
– A binary operator has two input parameters.
• In each case, at least one parameter must have type T or T?
where T is the type that contains the operator declaration.

Slide 20
Overloadable Operators

Slide 21
Operator Overloading
public class Fraction
{
private readonly int num;
private readonly int den;

public Fraction(int numerator, int denominator)


{
if (denominator == 0)
{
throw new ArgumentException("Denominator cannot be zero.", nameof(denominator));
}
num = numerator;
den = denominator;
}

public static Fraction operator +(Fraction a) => a;

public static Fraction operator -(Fraction a) => new Fraction(-a.num, a.den);

public static Fraction operator +(Fraction a, Fraction b)


=> new Fraction(a.num * b.den + b.num * a.den, a.den * b.den);

Slide 22
Structs
• Structs are similar to classes in that they represent
data structures that can contain data members and
function members.
• A structure type (or struct type) is a value type that
can encapsulate data and related functionality.
• Structs are particularly useful for small data
structures that have value semantics.
– Complex numbers, points in a coordinate system, or key-
value pairs in a dictionary are all good examples of structs.

Slide 23
Structs
public struct Coords
{
public Coords(double x, double y)
{
X = x;
Y = y;
}

public double X { get; }


public double Y { get; }

public override string ToString() => $"({X}, {Y})";


}

Slide 24
readonly Struct
• You use the readonly modifier to declare that a
structure type is immutable.
• All data members of a readonly struct must be read-
only as follows:
• Any field declaration must have the readonly
modifier
• Any property, including auto-implemented ones,
must be read-only

Slide 25
readonly Struct
public readonly struct Coords
{
public Coords(double x, double y)
{
X = x;
Y = y;
}

public double X { get;} //or declare readonly


public double Y { get;}

public override string ToString() => $"({X}, {Y})";


}

Slide 26
Records
• Beginning with C# 9, you use the record modifier to
define a reference type that provides built-in
functionality for encapsulating data
• C# 10 allows the record class syntax as a synonym to
clarify a reference type, and record struct to define a
value type with similar functionality
• When you declare a primary constructor on a record,
the compiler generates public properties for the
primary constructor parameters
– The primary constructor parameters to a record are referred
to as positional parameters.
Slide 27
Records and Record Class
//Record
public record Person(string FirstName, string
LastName);

//Record Class
public record Person
{
public required string FirstName { get; init; }
public required string LastName { get; init; }
};

Slide 28
Record Struct Types
public readonly record struct Point(double X, double
Y, double Z);

public record struct Point


{
public double X { get; init; }
public double Y { get; init; }
public double Z { get; init; }
}

Slide 29
Sealed Modifier
When applied to a class, the sealed modifier prevents
other classes from inheriting from it.
In the following example, class B inherits from class A,
but no class can inherit from class B.

class A {}
sealed class B : A {}

Slide 30

You might also like