Search code examples
c#ooppolymorphism

Constructor prints text when object is created


I am working in a C# console application and I am learning OOP. First, I have a Person Class,

   class Person
   {
    public string Name;
    public string LastName;

    public void Comment()
    {
        Console.WriteLine("Comment from Person Class");
    }

and Student class

class Student : Person
{
    public int IndexNr = 171124;
    public int totalSubjects;

    public Student()
    {
        Console.WriteLine("Index number=" + IndexNr);
    }
    public Student(int subjectsTotal,int nr) 
    {
        totalSubjects= nr;
        Console.WriteLine("Average grade= " + subjectsTotal/ totalSubjects);
    }

    public void Comment()
    {
        Console.WriteLine("Comment from Student class");
    }

}

And in the Program.cs in the Main function the code goes like this:

    static void Main(string[] args)
    {

        Console.WriteLine("Student Info");

        Student st2= new Student();
        st2.Name= "name1";
        st2.LastName = "lastname1";
        Console.WriteLine("Name=" + st2.Name+ " LastName=" + st2.LastName);
        Student st1 = new Student(90,10);

        //Polymorphism example -> here is where I need help
        Person p1 =  new Person();
        Person s1 = new Student();
        

        p1.Komenti();
        s1.Komenti();

    }

So, when I create Person s1 = new Student() object it prints out the the Comment function from only Person class, and not 1 from Person and 1 from Student class.

I have tried the same in Java as well and there it works very well. Can you please tell me and enlighten me where am I making mistakes or what am I missing? Thank you.


Solution

  • Try using the override modifier on the Comment method in the Student class https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/override This should then override the person implementation

    public class Student : Person
    {
        public int IndexNr = 171124;
        public int totalSubjects;
    
        public Student()
        {
            Console.WriteLine("Index number=" + IndexNr);
        }
        public Student(int subjectsTotal,int nr) 
        {
            totalSubjects= nr;
            Console.WriteLine("Average grade= " + subjectsTotal/ totalSubjects);
        }
    
        public override void Comment()
        {
            Console.WriteLine("Comment from Student class");
        }
    
    }