Top Banner
Class A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope.
37
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Constructor

Class• A class is a construct that enables you to create your

own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope.

Page 2: Constructor

Objects• Objects are programming constructs that have

data, behavior, and identity. Object data is contained in the fields, properties, and events of the object, and object behaviors are defined by the methods and interfaces of the object.

• Objects have identity — two objects with the same set of data are not necessarily the same object.

• Objects in C# are defined through classes and structs — these form the single blueprint from which all objects of that type operate.

Page 3: Constructor

Constructor• A constructor initializes an object when it is created. It

has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type. The general form of a constructor is shown here:

access class-name(param-list) { // constructor code}

• This constructor is called by new keyword when an object is created. For example, in the line

• MyClass t1 = new MyClass();

Page 4: Constructor

Parameterized Constructors/ Overloaded constructor

• class MyClass {

• public int x;

• public MyClass(int i) {

• x = i;

• }

• }

Page 5: Constructor

Static Constructors• A constructor can also be specified as static. A static

constructor is typically used to initialize features that apply to a class rather than an instance. Thus, it is used to initialize aspects of a class before any objects of the class are created. Here is a simple example:

using System;class Cons { public static int alpha;

public int beta; // A static constructor.

static Cons() { alpha = 99; Console.WriteLine("Inside static constructor."); }

Page 6: Constructor

• // An instance constructor.• public Cons() {• beta = 100;• Console.WriteLine("Inside instance constructor.");• }• }• class ConsDemo {• static void Main() {• Cons ob = new Cons();• Console.WriteLine("Cons.alpha: " + Cons.alpha);• Console.WriteLine("ob.beta: " + ob.beta);• }• }

• Here is the output:• Inside static constructor.• Inside instance constructor.• Cons.alpha: 99• ob.beta: 100

Page 7: Constructor

Static Classes• A class can be declared static. There are two key

features of a static class. • First, no object of a static class can be created. • Second, a static class must contain only static

members. A static class is created by modifying a class declaration with the keyword static, shown here:

• static class Program• {• static void Main(string[] args)• {• Console.WriteLine("this is static class constructor");• }• }

Page 8: Constructor

Constructor Chaining• When working with overloaded constructors, it is

sometimes useful for one constructor to invoke another.

• In C#, this is accomplished by using another form of the this keyword.

• When the constructor is executed, the overloaded constructor that matches the parameter list specified by parameter-list2is first executed.

• Then, if there are any statements inside the original constructor, they are executed.

Page 9: Constructor

• class Car• {• private string description;• private uint nWheels;• public Car(string model, uint nWheels)• {• this.description = description;• this.nWheels = nWheels;• }• public Car(string model) : this(model, 4)• {}

• Car myCar = new Car(“Proton Persona”);

Page 10: Constructor

Private Constructors

• In C# there are no global methods or constants. You might find yourself creating small utility classes that exist only to hold static members. Setting aside whether this is a good design or not, if you create such a class you will not want any instances created.

• You can prevent any instances from being created by creating a default constructor (one with no parameters) which does nothing, and which is marked private. With no public constructors, it will not be possible to create an instance of your class.

Page 11: Constructor

readonly• You can create a read-only field in a class by

declaring it as readonly.• A readonly field can be given a value only by

using an initializer when it is declared or by assigning it a value within a constructor.

• Once the value has been set, it can’t be changed outside the constructor.

• Thus, a readonly field is a good way to create a fixed value that has its value set by a constructor.

Page 12: Constructor

• using System;• class MyClass {• public static readonly int SIZE = 10;• }• class DemoReadOnly {• static void Main() {• int[] source = new int[MyClass.SIZE];• • for(int i=0; i < MyClass.SIZE; i++)• source[i] = i; // Give source some values. • foreach(int i in source)• Console.Write(i + " ");• Console.WriteLine();

Page 13: Constructor

Passing by Reference• C# provides the ref parameter modifier for

passing value into a method by reference and the out modifier for those cases in which you want to pass in a ref variable without first initializing it.

• The ref parameter modifier causes C# to create a call-by-reference, rather than a call-by-value. The ref modifier is specified when the method is declared and when it is called.

Page 14: Constructor

Use refclass RefTest {

// This method changes its argument. Notice the use of ref.

public void Sqr(ref int i) { i = i * i; }}

class RefDemo { static void Main() { RefTest ob = new RefTest(); int a = 10; Console.WriteLine("a before call: " + a);

ob.Sqr(ref a); // notice the use of ref

Console.WriteLine("a after call: " + a); }}

outputa before call: 10a after call: 100

Page 15: Constructor

Out• The out modifier removes the requirement that

a reference parameter be initiailzed.• The parameters to GetTime( ), for example,

provide no information to the method; they are simply a mechanism for getting information out of it.

• Thus, by marking all three as out parameters, you eliminate the need to initialize them outside the method.

• Within the called method the out parameters must be assigned a value before the method returns. Here are the altered parameter declarations for GetTime( ):

Page 16: Constructor

• class Decompose {• public int GetParts(double n, out double frac) {• int whole;• whole = (int) n;• frac = n - whole; // pass fractional part back through frac• return whole; // return integer portion• }}• class UseOut {• static void Main() {• Decompose ob = new Decompose();• int i;• double f;• i = ob.GetParts(10.125, out f);• Console.WriteLine("Integer portion is " + i);• Console.WriteLine("Fractional part is " + f);• }}

Page 17: Constructor

Reference Parameter

int theHour = 0;

int theMinute = 0;

int theSecond = 0;

t.GetTime( ref theHour, ref theMinute, ref theSecond);

Out Parameter

public void GetTime(out int h, out int m, out int s)

{

h = Hour;

m = Minute;

s = Second;

}

Page 18: Constructor

Ref/ Out• Value types are passed into methods by

value. Ref parameters are used to pass value types into a method by reference. This allows you to retrieve their modified value in the calling Programming C# method.

• Out parameters are used only to return information from a method.

Page 19: Constructor

Calling Base Class Constructors• A derived class can call a constructor

defined in its base class by using an expanded form of the derived class’ constructor declaration and the base keyword.

derived-constructor (parameter-list ) : base( arg-list ) {

// body of constructor

}

Page 20: Constructor

• arg-list specifies any arguments needed by the constructor in the base class.

• Notice the placement of the colon.

class Program

{

public int i=0, j=0;

public Program(int a, int b)

{ i = a; j = b; }

public void show1()

{ Console.WriteLine(“Base class"+i+j);

} }

Page 21: Constructor

class D:Program

{

string s1;

public D(string s, int a, int b): base(a, b)

{ s1 = s; }

public void sh()

{ Console.WriteLine(s1+i+j); }

static void Main(string[] args)

{

D d1 = new D(“Drive Class ", 5, 8);

d1.sh();} }

Page 22: Constructor
Page 23: Constructor

Name Hiding• It is possible for a derived class to define a

member that has the same name as a member in its base class.

• When this happens, the member in the base class is hidden within the derived class.

• If your intent (goal or aim) is to hide a base class member, then to prevent warning, the derived class member must be preceded by the new keyword.

• Understand that this use of new is separate and distinct

from its use when creating an object instance.

Page 24: Constructor

class A {

public int i = 0; }

class B : A {

new int i;

public B(int b) { i = b; }

public void Show() {

Console.WriteLine("i in derived class: " + i);

}}

class NameH {

static void Main() {

B ob = new B(2);

ob.Show();

}}

Page 25: Constructor

Access a Hidden Name• using System;

• class A { public int i = 0; }

• class B : A {

• new int i;

• public B(int a, int b) {

• base.i = a; // this uncovers the i in A

• i = b; // i in B

• }

Page 26: Constructor

public void Show() {

Console.WriteLine("i in base class: " + base.i);

Console.WriteLine("i in derived class: " + i);

}}

class UncoverName {

static void Main() {

B ob = new B(1, 2);

ob.Show();

}}

Page 27: Constructor

Hidden Methodclass A { public int i = 0;

public void Show() {

Console.WriteLine("i in base class: " + i);

}}

class B : A {

new int i;

public B(int a, int b) {

base.i = a;

i = b; }

Page 28: Constructor

new public void Show() { base.Show(); // this calls Show() in A

// this displays the i in B

Console.WriteLine("i in derived class: " + i);

}}

class UncoverName {

static void Main() {

B ob = new B(1, 2);

ob.Show();

}}

Page 29: Constructor

Overridden method• Polymorphism is essential to object-oriented

programming for one reason: It allows a general class to specify methods that will be common to all of its derivatives, while allowing derived classes to define the specific implementation of some or all of those methods.

• Overridden methods are another way that C# implements the “one interface, multiple methods” aspect of polymorphism.

Page 30: Constructor

Virtual Methods and Overriding• A virtual method is a method that is

declared as virtual in a base class.

• The defining characteristic of a virtual method is that it can be redefined in one or more derived classes.

• You declare a method as virtual inside a base class by preceding its declaration with the keyword virtual.

• When a virtual method is redefined by a derived class, the override modifier is used.

Page 31: Constructor

• Thus, the process of redefining a virtual method inside a derived class is called method overriding.

• When overriding a method, the name, return type, and signature of the overriding method must be the same as the virtual method that is being overridden.

• Also, a virtual method cannot be specified as static or abstract.

Page 32: Constructor

• Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at runtime, rather than compile time.

• Dynamic method dispatch is important because this is how C# implements runtime polymorphism.

Page 33: Constructor

class Base {

public virtual void Who() {

Console.WriteLine("Who() in Base");

}}

class Derived1 : Base {

public override void Who() {

Console.WriteLine("Who() in Derived1");

}}

class Derived2 : Base {

public override void Who() {

Console.WriteLine("Who() in Derived2"); }}

Page 34: Constructor

class OverrideDemo {

static void Main() {

Base baseOb = new Base();

Derived1 dOb1 = new Derived1();

Derived2 dOb2 = new Derived2();

Base baseRef; // a base class reference

baseRef = baseOb;

baseRef.Who();

baseRef = dOb1;

baseRef.Who();

baseRef = dOb2;

baseRef.Who(); }}

Page 35: Constructor
Page 36: Constructor

• Inside the Main( ) method, objects of type Base, Derived1, and Derived2 are declared. Also,

• a reference of type Base, called baseRef , is declared. The program then assigns a reference to each type of object to baseRef and uses that reference to call Who( ).

• the version of Who( ) executed is determined by the type of object being referred to at the time of the call, not by the class type of baseRef .

Page 37: Constructor

sealed• class B {

• public virtual void MyMethod() { /* ... */ }

• }

• class D : B {• // This seals MyMethod() and prevents further overrides.

• sealed public override void MyMethod() { /* ... */ }}

• class X : D {• // Error! MyMethod() is sealed!

• public override void MyMethod() { /* ... */ }}