Inherited doubts

I am relatively new to OOP, so I wanted to clarify a few things

I have the following code snippet

class Parent
{
     public Parent()
     {
           Console.WriteLine("Parent Class constructor");
     }

     public void Print()
     {
            Console.WriteLine("Parent->Print()");
     }
}

class Child : Parent
{
     public Child() 
     {
          Console.WriteLine("Child class constructor");
     }

     public static void Main()
     {
           Child ChildObject = new Child();
           Parent ParentObject = new Child();

           ChildObject.Print();
           ParentObject.Print();
     }

}

Output:

Parent Class Constructor
Child Class constructor

Parent Class Constructor
Child Class constructor

Parent->Print()
Parent->Print()

My questions are as follows:

1) Why is the constructor of the base class called when creating objects using the constructor ChildClass? without explicit keyword base. Is there a way to avoid calling the base class constructor?

2) why is it possible ParentClass ParentObj = new ChildClass();? and not vice versa.

+5
source share
6 answers

In short, polymorphism .

Child Parent, . , .

1) ChildClass? base. ?

( ). ( , , ..).

2) ParentClass ParentObj = new ChildClass(); ? .

- Child Parent Parent. Parent Child, Parent Child Child.

, . , , Parent , Child .

+4
  • , . , , .

  • ChildClass " ParentClass. " is-a", .

+6
  • : base(), .
    : base("foo"), Parent(string s), Parent() . , .
  • Animal animal = new Dog(); , Dog dog = new Animal(); , .
+3

1) , , /. Child/Parent ( ). - Is-A. - . , .

2) , , , . , , .

+1

1) ( ) , , . , , .

2) ChildClass ParentClass, Square Rectangle. , . .

0

1) In C #, if you do not specify a call to another constructor using something like base(blah), it will call the default constructor. What you defined above.

2) Everyone ChildClasswill always be ParentClass. However, there may be objects that are ParentClass, but are not ChildClass. For example, if you have OtherChildClass : ParentClass, it will ParentClass, but it will not ChildClass.

0
source

All Articles