C ා learning notes [5] - object oriented programming

Posted by almora on Sat, 26 Oct 2019 13:07:50 +0200

5.1 definition and declaration of class

5.1.1 constructor

When we construct an object, the initialization process of the object is automatically completed. However, in the process of initializing the object, we need to do some extra work, such as initializing the data stored in the object. The constructor is the function used to initialize the data.

The syntax of declaring a basic constructor is to declare a method with the same name as the class, but the method has no return type.

public class MyClass{

    public MyClass(){

The function body of this constructor

    }

}

When we use the new keyword to create a class, we call the constructor.

In general, we use construction methods to initialize data.

The constructor can be overloaded, which is the same rule as ordinary function overloads.

When we do not write any constructors, the compiler will provide us with a default parameterless constructor, but if we define one or more constructors, the compiler will not provide a default constructor.

5.1.2 definition of attributes

Attribute definition structure:

    public int MyIntProp{

       get{

           // get code

       }

       set{

           //set code

       }

    }

Name and type are required to define properties.

The attribute contains two block get and set blocks.

Accessing attributes is the same as accessing fields. When we get the value of an attribute, we will call the get block in the attribute. Therefore, the type of the get block requires a return value that is the attribute type. When we set the value of an attribute, we will call the set block in the attribute. We can access the value we set in the set block through value.

5.1.3 accessing fields through attributes

We are used to setting the field as private, so that the value of the field cannot be modified by the outside world. Then we can set and get the value of the field by defining the property.

private int age;

public int Age {/ / property upper case field lower case

    set{

       if(value<0)return;

       age = value;

    }

    get{

       return age;

    }

}

5.1.4 set read-only or write only properties

Property can only provide one set block or get block

5.1.5 attribute access decoration

5.1.6 anonymous type

When we create variables (objects), we must specify the type. In fact, we can not specify the type. This is anonymous type. We can use var to declare an anonymous type.

Use the anonymous type declared by var. when initializing, the type of this variable will be determined and cannot be modified later.

var v = new Vehicle();
var v1 = "Lemon";
//var v1 = 1; / / not allowed here, the type of v1 has been determined as string

public class Vector3//Set to public so that it can be accessed in other projects
    {
        //We have defined a constructor, so the compiler will not provide us with a constructor.
        public Vector3()
        {
            Console.WriteLine("Vector3 Constructor of is called");
        }

        public Vector3(float x, float y, float z)
        {
            this.x = x;
            this.y = y;
            this.z = z;
            length = Length();
        }

        //In the programming specification, it is customary to set all fields as private, which can only be accessed inside the class, not through the object.
        private float x, y, z, length;
        private int age;
        //private string name;

        //public String Name
        //{
        //    Get {return name;} / / you can get the value of a property through an object
        //    Private set {name = value;} / / you can only set the value of a property within a class
        //

        public string Name { get; set; }//The compiler will automatically provide us with a field to store name (note that we did not define name when defining the word / / segment).

        public int Age
        {
            set
            {
                //Do some verification work before setting the value through the set method
                if (value >= 0)
                {
                    age = value;
                }
            }
        }


        public float X// It can also be called get set method
        {
            get { return x; }
            set { x = value; }//If you add private before get or set, this block can only be called inside the class.

        }

        //Provide a set method for the field to set the value of the field

        public void SetX(float x)

        {
            //If we access a variable with the same name directly inside the method, we have priority to access the nearest (parameter).
            //We can access the fields or methods of the class through this.
            this.x = x;

        }


        public void SetY(float y)
        {
            this.y = y;
        }


        public void SetZ(float z)
        {
            this.z = z;
        }


        public float Length() {
            return (float)Math.Sqrt(x * x + y * y + z * z);
        }

        //Defining attributes
        public int MyIntProperty {
            set {
                Console.WriteLine("Attribute set Block is invoked");
                Console.WriteLine("stay set Block access value The value is:"+value);
            }
            //If there is no get block, the value cannot be obtained through the attribute.
            get {
                Console.WriteLine("Attribute get Block is invoked ");
                return 100;
            }
        }
}

5.2 inheritance

5.2.1 types of inheritance

Implement inheritance:

Indicates that a type derives from a base type, which has all the member fields and functions of the base type. In implementation inheritance, the derived type takes the implementation code of each function of the base type, unless the implementation code overriding a function is specified in the definition of the derived type. This type inheritance is useful when you need to add functionality to an existing type, or when many related types share an important set of common functions.

namespace c_sharp_001

{

    class Enemy

    {

        private int hp;

        private int speed;


        public int Hp

        {

            get { return hp; }

            set { hp = value; }

        }


        public int Speed

        {

            get { return speed; }

            set { speed = value; }

        }


        public void AI()

        {

            Console.WriteLine("Here is Enemy1 Public owned AI Method");

        }


        public void MoveI()

        {

            Console.WriteLine("Here is Enemy Public owned Move Method");

        }

    }

}

namespace c_sharp_001

{

    class Boss:Enemy

    {

        public void Attack()

        {

            //hp = 100;

            Hp = 100;//The public data and function members in the parent class can only be accessed in the child class.

            AI();

            MoveI();

            Console.WriteLine("Boss Attacking");

        }

    }

}

namespace c_sharp_001

{

    class Type1Enemy:Enemy

    {

    }

}

namespace c_sharp_001

{

    class Program

    {

        static void Main(string[] args)

        {

            Boss boss = new Boss();

            boss.AI();

            boss.Attack();


            Enemy enemy;

            enemy = new Boss();//The object declared by the parent class can be constructed by the child class                    

            Boss bossEnemy = (Boss)enemy;//Although nemy uses the parent class for declaration, it is essentially a

                                         //Subclass type, we can force type to subclass type


            Enemy enemy1 = new Enemy();

            Boss bossEnemy1 = (Boss)enemy1;//Cast error, what type an object is, mainly depends on what it is constructed through


            Console.ReadKey();

        }

    }

}

Interface inheritance:

Indicates that a type only inherits the signature of a function, and does not inherit any implementation code. It is best to use inheritance of this type when you need to specify that it has some available properties.

Multiple inheritance (not supported by C)

Some languages (c + +) support so-called "multiple inheritance", that is, a class derives from multiple classes. The advantages of using multiple inheritance are controversial: on the one hand, there is no doubt that you can use multiple inheritance to write very complex but compact code. On the other hand, code that uses multiple implementation inheritance is often difficult to understand and debug. As mentioned before, simplifying the writing of robust code is an important design goal of developing c ා. Therefore, C ා does not support multiple implementation inheritance. C allows types to derive from multiple interfaces -- multiple interface inheritance. This shows that the C ා class can be derived from another class and any number of interfaces. To be more precise, System.Object is a common base class, so every C (except for the object class) has a base class and any number of base interfaces.

5.3 virtual method

If you declare a base class function as virtual, you can override it in any derived class:

    class MyBaseClass{

       public virtual string VirtualMethod(){

           return "Method is called in base class";

       }

    }

When overriding another function in a derived class, use the override keyword to display the declaration

    class MyDerivedClass:MyBaseClass{ 

       public override string VirtualMethod(){

           return "Method is called in derivedclass.";

       }

    }

After we rewrite the virtual function in the subclass, no matter where we call it, we call the rewritten method.

namespace c_sharp_001

{

    class Enemy

{

        public void AI()

        {

            Move();

            Console.WriteLine("Here is Enemy1 Public owned AI Method");

    }


        public virtual void Move()

        {

            Console.WriteLine("Here is Enemy Public owned Move Method");

        }

    }

}

namespace c_sharp_001

{

    class Boss:Enemy

    {

        public override void Move()//Rewrite: the original method does not exist

        {

            Console.WriteLine("Here is Boss Move method of");

        }

        public void Attack()

        {

            Move();//Override Move in subclass, and call Move function in subclass

            Console.WriteLine("Boss Attacking");

        }

    }

}

namespace c_sharp_001

{

    class Program

    {

        static void Main(string[] args)

        {

            Boss boss = new Boss();

            boss.Attack();

            boss.AI();//Move method called by AI method in parent class has been overridden in child class

                      //After we rewrite the virtual function in the subclass, no matter where we call it, we call the rewritten method.


            Enemy enemy = new Enemy();

            enemy.AI();//The Move method overridden in a subclass does not affect the objects constructed by the parent class

            Console.ReadKey();

        }

    }

}

5.4 hiding method

If a method with the same signature (that is, the definition of the method, return value, parameter, method name) is declared in both the base class and the derived class, but the method is not declared as virtual and override respectively, the derived class will hide the base class method. (to declare using the new keyword)

Base class

    class MyBaseClass{

        public int MyMethod(){

        }

    }

Derived class (the method with the same name of the base class is hidden in the derived class)

    class MyDerivedClass :MyBaseClass{

        public new void MyMethod()        {

               }   

    }

namespace c_sharp_001

{

    class Enemy

    {

        public void Move()

        {

            Console.WriteLine("Here is Enemy Public owned Move Method");

        }

    }

}

namespace c_sharp_001

{

    class Boss:Enemy

    {

        public new void Move()//When a subclass has a method with the same signature as the parent, the method in the parent will be hidden.

        {                     //Hide: the original method still exists, but the method in the parent class is hidden.

            Console.WriteLine("Here is Boss Move method of");

        }

    }

}

namespace c_sharp_001

{

    class Program

    {

        static void Main(string[] args)

        {

            Boss boss = new Boss();

            boss.Move();//Using the object declared by the subclass, calling the hidden method will call the


            Enemy boss1 = new Boss();

            boss1.Move();//Using the object declared by the parent class, calling the hidden method will call the


            Console.ReadKey();

        }

    }

}

5.5.this and base keywords

This can access the fields, properties and methods defined in the current class. If there is this, you can access it. If there is this, you can ask the IDE vs compiler to give a prompt. In addition, when the parameter of the method has the same name as the field, use this to indicate that the field in the class is accessed.

Base can call the public methods and fields in the parent class. If there is a base, you can access it. But with the help of base.IED, you will be prompted to list all the fields and methods that can be called for easy selection.

5.6 abstract class

C allows classes and functions to be declared abstract. Abstract class cannot be instantiated. Abstract class can contain ordinary function and abstract function. Abstract function is only function definition without function body. Obviously, the abstract function itself is virtual (only function definition, no function body implementation).

A class is a template, so an abstract class is an incomplete template. We cannot use incomplete templates to construct objects.

    abstract class Building{

        public abstract decimal CalculateHeatingCost();

namespace c_sharp_001

{

    abstract class Bird//abstract class

    {

        private float speed;


        public void Eat()

        {


        }

        public abstract void Fly();

    }

}

namespace c_sharp_001

{

    class Crow : Bird//If you inherit an abstract class, you must implement the abstract method.

    {

        public override void Fly()

        {

            Console.WriteLine("Crows are flying");

        }

    }

}

namespace c_sharp_001

{

    class Program

    {

        static void Main(string[] args)

        {

            Crow crow = new Crow();

            crow.Fly();


            Bird bird = new Crow();//Objects can be declared through abstract classes, but not constructed

            bird.Fly();


            Console.ReadKey();

        }

    }

}

5.7 sealing type and method

C allows classes and methods to be declared sealed. For a class, this means that the class cannot be inherited; for a method (declaring the overridden method as sealed), it means that the method cannot be overridden again. Prevent code clutter or business reasons from overriding certain classes

    sealed FinalClass

    {

       // etc

    }

5.8 constructors of derived classes

In the subclass, we call the default constructor of the parent class (without reference), which calls the parent class first and then the subclass.

    public class MyDerivedClass{

       public MyDerivedClass():base(){

           //do something

       }

    }

Here: base() can not write directly, because it will call the default constructor in the parent class by default

Call constructor with parameters

    public class MyDerivedClass{

       public MyDerivedClass(string name):base(name){

           //do something

       }

    }

namespace c_sharp_001

{

    class BaseClass

    {

        private int x;

        public BaseClass()

        {

            Console.WriteLine("BaseClass non-parameter constructor ");

        }

        public BaseClass(int x)

        {

            this.x = x;

            Console.WriteLine("x Assignment completion");

        }

    }

}

namespace c_sharp_001

{

    class DerivedClass:BaseClass

    {

        private int y;

        public DerivedClass() : base()//Call the parameterless constructor in the parent class

        {                             //When the constructor of the calling parent class is not displayed in the child class, the nonparametric constructor of the parent class will be called by default

            Console.WriteLine("DerivedClass non-parameter constructor ");

        }

        public DerivedClass(int x,int y):base(x)

        {

            this.y = y;

            Console.WriteLine("y Assignment completion");

        }

    }

}

5.9 modifiers

Protected. When there is no inheritance, it has the same function as private. When there is inheritance, protected represents the fields or methods that can be accessed by subclasses.

Static can modify a field or method. When modifying a field, it means that the field is static data, which is called static field or static property. When modifying a method, it is called static method or static function. Members decorated with static can only be accessed through the class name. When we construct an object, only ordinary fields are included in the object, not static fields.

5.10 interface

Defining an interface is the same as defining an abstract class in syntax, but it is not allowed to provide the implementation of any member of the interface. Generally, an interface can only contain the declaration of methods, properties, indexers and events (abstract methods).

An interface cannot have a constructor, a field, or an operator overload.

The modifier of a member is not allowed to be declared in the interface definition. All interface members are public.

Interfaces can inherit from each other in the same way as classes.

namespace c_sharp_001

{

    interface IFly

    {

        void Fly1();//Not modifiable with modifier, default public

        void Fly2();

    }

}

namespace c_sharp_001

{

    interface IA

    {

        void MethodA();

    }

}

namespace c_sharp_001

{

    interface IB:IA

    {

        void MethodB();

    }

}

namespace c_sharp_001

{

    class Bird : IFly,IB//All methods in the interface in the class to implement its inheritance

    {

        public void Fly1()

        {

        }

        public void Fly2()

        {

        }

        public void MethodA()//IB method inherited from IA

        {

        }

        public void MethodB()//Method in IB

        {

        }

    }

}

 

Topics: Attribute Programming