In this one lesson, we learned about the three main features of C # in specific applications and object-oriented (OOP) aspects of classes: encapsulation (encapsulation), polymorphism (polymorphism), and Inheritance (inheritance). Next, let's experiment with what we've learned.
(i) this keyword
The This keyword (also known as the This pointer) is a hidden pointer to all non-static methods in the class.
There are many ways to call this, first, when you receive a parameter with the same name as a member variable, using this to avoid confusion, as demonstrated in the following procedure:
The member function SomeMethod received a parameter with the same name as the member variable hour, which solves the problem of name confusion well by This.hour method.
Another usage is to explicitly invoke a method and member of a class when you can use the this pointer, for example:
This.z = 5; Assign a value to a member variable
This. Draw (); Call a member method
(ii) Use of static members:
A static member differs from a normal member variable, which is a variable that belongs to the class itself and not to the object, and can often help us to count the number of objects.
From this we can see that by changing the value of count in the constructor, we can achieve the purpose of counting the number of objects created.
(iii) Problem of transfer of parameters in C #:
The class object that you create in C # is passed by value by default, even if you do not write Val, and are passed by value in the same way.
For example, just like we showed you how to pass parameters in C #.
(iv) Some issues relating to new, virtual and override:
If we have some of the following code, which includes new, virtual, and override, can you guess the correct result without looking at the output:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Namespace ConsoleApplication3
{
Class Program
{
Class A
{
public virtual void Fruit ()
{
Console.WriteLine ("Apple");
}
}
Class B:a
{
public override void Fruit ()
{
Console.WriteLine ("Banana");
}
}
Class C:b
{
Public new virtual void Fruit ()
{
Console.WriteLine ("Orange");
}
}
Class D:c
{
public override void Fruit ()
{
Console.WriteLine ("Pear");
}
}
Class Testme
{
static void Main (string[] args)
{
A obja = new D ();
A OBJB = new B ();
C OBJC = new D ();
A objd = new A ();
Obja.fruit ();
Objb.fruit ();
Objc.fruit ();
Objd.fruit ();
}
}
}
}
If you want to know what these outputs are, it is important to know that override will invoke the overriding function in any case, either in the subtype or in the parent type. After understanding this, it is not difficult to think of the output of the above code:
Liam's C # Learning Journey (iii): Classes and objects, inheritance and polymorphism