#437 – Access Interface Members through an Interface Variable

Once a class implements a particular interface, you can interact with the members of the interface through any instance of that class.

            Cow bossie = new Cow("Bossie", 5);

            // Cow implements IMoo, which includes Moo method
            bossie.Moo();

You can also declare a variable whose type is an interface, assign it to an instance of any class that implements that interface and then interact with members of the interface through that interface variable.

            // bossie is a Cow, which implements IMoo, so we can point IMoo variable at her
            IMoo mooer = bossie;
            mooer.Moo();

In either case, we end up calling the same Moo method.

Notice that we can’t access members of Cow that aren’t part of IMoo using this interface variable.

Even though MakeSomeMilk is a public method in the Cow class, we can’t access it via IMoo.

Advertisement