0

I have to vrite an override function for my function DajGlos(), but I get back error CS0120 (An object reference is required for the non-static field, method, or property). How can I fix this?

My code:

 static void Main(string[] args)
        {
            Pies pies = new Pies("Reksio", "ssaki", "lądowe", 50);

            Pies.Przedstaw("Reksio", "ssaki", "lądowe");
            Pies.DajGlos();
        }

    abstract class Zwierze
    {
        private static string Rodzina { get; set; }
        private static string Grupa { get; set; }
        private static string Imie { get; set; }

        public static void Przedstaw(string Imie, string Rodzina, string Grupa)
        {
            Console.WriteLine("Jestem " + Imie + ", rodzina: " + Rodzina + ", grupa: " + Grupa);
        }

        public abstract void DajGlos();

    }

    class Pies : Zwierze
    {
        public Pies(string Imie, string Rodzina, string Grupa, int dlugoscOgona)
        {
            
        }
        int dlugoscOgona;

        public override void DajGlos()
        {
            Console.WriteLine("Bark!");
        }
    }```

inLwetrust
  • 11
  • 4
  • 1
    Because DajGlos is not static, unlike Przedstaw. So you need to refer to `pies` - the instance of the Pies class - in order to use it. – ADyson Dec 15 '20 at 22:19

2 Answers2

0

DajGlos is an instance method, so as the error message says, you need to call it on a specific instance (in your case - pies), not on the class itself. I.e.:

Pies pies = new Pies("Reksio", "ssaki", "lądowe", 50);
Pies.Przedstaw("Reksio", "ssaki", "lądowe");
pies.DajGlos(); // Here!
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

ClassName.StaticMethodName(...) is for accessing static methods.
ObjectName.NonStaticMethodName(...) is for accessing non-static methods.
The line Pies.DajGlos(); is ClassName.NonStaticMethodName(...) which is not allowed.
I guess what you were trying to do is: pies.DajGlos();.

Roy Cohen
  • 1,540
  • 1
  • 5
  • 22