In the specific case you site, I would have written "Dim myBook As Book = New Book". Acutally I would have written, "Dim myBook As New Book", but you get the point. The reason I would have done so is because the variable is declared locally and there is no need or benefit for restricting to the parent object. In my opinion, at this level it is a question of primarily of programer style.
What the article is doing is following a general principle. I.e. You get higher reuse and greater stability if you restrict your methods to relying on the most abstract view of an object. Since no property or method specific to Book is required by this method, it casts the new Book object as its parent LibraryAsset and uses just the properties and methods exposed by that parent. If Book overrides any LibraryAsset routines the Book version of the routine will be called instead of the Library Asset version. This general principle is very useful with method parameters or when dealing with non-private properties. For example, why restrict an paramter to being a partciular class when all you realy care about is that it implements a particular interface. For objects that are declared and used locally this prinicple is not as useful, but there's nothing wrong with following it even then. -- R.B. Davidson On May 6, 9:00 pm, Learner <[email protected]> wrote: > Hi, > > I am reading an article online and I have come across the below code > snippet. > > Public Sub ReturnBook(ByVal dueDate As DateTime) > > Dim myBook As LibraryAsset = New Book > > myBook.DueDate = dueDate > > Dim amountDue As Double = myBook.CalculateFineTotal() > > Console.WriteLine("Book: {0}", amountDue.ToString()) > > End Sub > > I am kind of not sure if I understand the line of code Dim myBook As > LibraryAsset = New Book right. In which LibraryAsset is the base class > and Book is the derived class. LibraryAsset class is a MustInherit > class with a overridable function in it. > > Instead of the line Dim myBook As LibraryAsset = New Book can't we > code like > > Dim myBook As Book = New Book ? Why do we have to assign a New Book > instance to LibraryAsset? > > In other words if I have a base class X and a derived class Y inorder > for me to instantiate Y in another class do I have to use > > Dim y1 as X = New Y but not Dim y1 as Y = New Y? > > Please explain this. I am bit new to OOP techniques. > > Thanks, > > -L
