Class
• A class is a construct that enables you to create your
own custom types by grouping together variables of
other ty...
Objects
• Objects are programming constructs that have
data, behavior, and identity. Object data is
contained in the field...
Constructor
• A constructor initializes an object when it is created. It
has the same name as its class and is syntactical...
Parameterized Constructors/
Overloaded constructor
• class MyClass {
• public int x;
• public MyClass(int i) {
•
x = i;
• ...
Static Constructors
• A constructor can also be specified as static. A static
constructor is typically used to initialize ...
•
•
•
•
•
•
•
•
•
•
•
•
•

// An instance constructor.
public Cons() {
beta = 100;
Console.WriteLine("Inside instance cons...
Static Classes
• A class can be declared static. There are two key
features of a static class.
• First, no object of a sta...
Constructor Chaining
• When working with overloaded constructors, it is
sometimes useful for one constructor to invoke
ano...
•
•
•
•
•
•
•
•
•
•
•

class Car
{
private string description;
private uint nWheels;
public Car(string model, uint nWheels...
Private Constructors
• In C# there are no global methods or constants.
You might find yourself creating small utility
clas...
readonly
• You can create a read-only field in a class by
declaring it as readonly.
• A readonly field can be given a valu...
•
•
•
•
•
•
•
•
•
•
•
•
•

using System;
class MyClass {
public static readonly int SIZE = 10;
}
class DemoReadOnly {
stat...
Passing by Reference
• C# provides the ref parameter modifier for
passing value into a method by reference
and the out mod...
Use ref
class RefTest {
// This method changes its argument. Notice the use of ref.

public void Sqr(ref int i) {
i = i * ...
Out
• The out modifier removes the requirement that
a reference parameter be initiailzed.
• The parameters to GetTime( ), ...
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•

class Decompose {
public int GetParts(double n, out double frac) {
int whole;
whole = (in...
Reference Parameter
int theHour = 0;
int theMinute = 0;
int theSecond = 0;
t.GetTime( ref theHour, ref theMinute, ref theS...
Ref/ Out
• Value types are passed into methods by
value. Ref parameters are used to pass
value types into a method by refe...
Calling Base Class Constructors
• A derived class can call a constructor
defined in its base class by using an
expanded fo...
• arg-list specifies any arguments needed
by the constructor in the base class.
• Notice the placement of the colon.
class...
class D:Program
{
string s1;
public D(string s, int a, int b): base(a, b)
{
s1 = s;
}
public void sh()
{ Console.WriteLine...
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.
...
class A {
public int i = 0;
class B : A {
new int i;
public B(int b) {

}

i = b;

public void Show() {
Console.WriteLine(...
Access a Hidden Name
• using System;
• class A { public int i = 0;
}
• class B : A {
• new int i;
• public B(int a, int b)...
public void Show() {
Console.WriteLine("i in base class: " + base.i);
Console.WriteLine("i in derived class: " + i);
}}
cl...
Hidden Method
class A { public int i = 0;
public void Show() {
Console.WriteLine("i in base class: " + i);
}}
class B : A ...
new public void Show() {
base.Show(); // this calls Show() in A
// this displays the i in B

Console.WriteLine("i in deriv...
Overridden method
• Polymorphism is essential to object-oriented
programming for one reason: It allows a
general class to ...
Virtual Methods and Overriding
• A virtual method is a method that is
declared as virtual in a base class.
• The defining ...
• Thus, the process of redefining a virtual
method inside a derived class is called
method overriding.
• When overriding a...
• Dynamic method dispatch is the
mechanism by which a call to an
overridden method is resolved at runtime,
rather than com...
class Base {
public virtual void Who() {
Console.WriteLine("Who() in Base");
}}
class Derived1 : Base {
public override vo...
class OverrideDemo {
static void Main() {
Base baseOb = new Base();
Derived1 dOb1 = new Derived1();
Derived2 dOb2 = new De...
• Inside the Main( ) method, objects of type
Base, Derived1, and Derived2 are
declared. Also,
• a reference of type Base, ...
sealed
• class B {
• public virtual void MyMethod() { /* ... */ }
• }
• class D : B {
•

•

// This seals MyMethod() and p...
Constructor
Constructor
Upcoming SlideShare
Loading in …5
×

Constructor

384 views

Published on

Published in: Education, Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
384
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
7
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Constructor

  1. 1. 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.
  2. 2. 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.
  3. 3. 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();
  4. 4. Parameterized Constructors/ Overloaded constructor • class MyClass { • public int x; • public MyClass(int i) { • x = i; • } • }
  5. 5. 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."); }
  6. 6. • • • • • • • • • • • • • // 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
  7. 7. 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"); • } • }
  8. 8. 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.
  9. 9. • • • • • • • • • • • 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”);
  10. 10. 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.
  11. 11. 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.
  12. 12. • • • • • • • • • • • • • 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();
  13. 13. 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.
  14. 14. Use ref class 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); } } output a before call: 10 a after call: 100
  15. 15. 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( ):
  16. 16. • • • • • • • • • • • • • • • • 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); }}
  17. 17. 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; }
  18. 18. 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.
  19. 19. 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 }
  20. 20. • 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); } }
  21. 21. 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();} }
  22. 22. 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.
  23. 23. 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(); }} }
  24. 24. 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 • }
  25. 25. 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(); }}
  26. 26. Hidden Method class 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; }
  27. 27. 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(); }}
  28. 28. 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.
  29. 29. 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.
  30. 30. • 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.
  31. 31. • 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.
  32. 32. 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"); }}
  33. 33. 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(); }}
  34. 34. • 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 .
  35. 35. 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() { /* ... */ }}

×