O'Reilly logo

Object-Oriented Programming with Visual Basic .NET by J.P. Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.1. Private Implementation

The IPaintable interface was defined as Public. In Example 5-2, methods are implemented as Public, too. This implementation allows you to call interface members through an instance of an object:

Dim myCar As New Car( )
myCar.Paint(Color.LemonChiffon)

One school of thought says that a client should not be aware of objects. It should only know about interfaces, and all interaction with an object should be made through an interface reference instead of an object reference. While this example is extreme, it has a point. By now, you can probably guess that using interface references rather than object references enhances encapsulation. In this case, there is less of a dependency between the client and the object.

Just because an interface is public doesn't mean you have to implement it publicly. Implementing the interface privately is actually better. If you make every method implemented in Example 5-2 private, you can no longer access the IPaintable methods directly. You have to use a reference to the interface, as the following code fragment illustrates:

Dim myCar as New Car( )
.  
.  
Dim paintable As IPaintable = myCar
.  
.  
paintable.Paint(Color.PapayaWhip)

Yes, this fragment lives in an unnatural setting. However, imagine client code that is only interface-aware. Think about how easy it would be to swap out new implementations without breaking anything. The key is that you do not care about what type of object you use; rather, you care about what the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required