Creating Classes, Object Construction & Destruction: Properties, Methods, Events

A VB.NET class packs fields, Sub New construction, methods and events, and adds the Property block: field-like syntax outside, full Get/Set control inside, where negative prices go to be refused.

12 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

The screen has no memory

Unit 3 built a beautiful till, but look where the data lives: scattered across txtItem.Text, txtQty.Text, grid rows. There is no THING in the program that IS a soap bar with its name and price.

BCA403 taught you the cure: model the real thing as a class. ShopKeeper needs an Item, then a Bill.

VB.NET's classes hold what Java's did (fields, constructors, methods) plus 2 members Java never had as syntax: Properties and Events. Both are this lesson.

Practical

The Item class, all members at once

Public Class Item
    Public Name As String              ' field
    Private _price As Decimal          ' backing field, hidden

    Public Sub New(ByVal name As String, ByVal price As Decimal)
        Me.Name = name                 ' constructor: Sub New
        _price = price
    End Sub

    Public Property Price As Decimal   ' the property
        Get
            Return _price
        End Get
        Set(value As Decimal)
            If value >= 0 Then _price = value   ' guard the till
        End Set
    End Property

    Public Function LineTotal(ByVal qty As Integer) As Decimal
        Return _price * qty            ' method
    End Function
End Class

' At the till:
' Dim soap As New Item("Soap", 40D)
' soap.Price = 35D      ' Set runs: accepted
' soap.Price = -5D      ' Set runs: guard refuses, still 35
' MsgBox(soap.LineTotal(3))   ' 105

Theory

Construction and (non-)destruction

Construction: the constructor is a Sub named exactly New. Dim soap As New Item("Soap", 40D) allocates the object and runs Sub New. Overload it like any procedure; and BCA403's vanishing-default rule applies here too: write any Sub New with parameters and the free no-arg one is gone.

Destruction: nothing for you to call. The garbage collector reclaims unreferenced objects, and may run a Protected Overrides Sub Finalize before doing so, at a time of ITS choosing. Exam phrase: destruction in .NET is non-deterministic.

Theory

Properties: the guarded doorway

Look at the property from both sides.

From outside, it reads like a field: soap.Price = 35D, Dim p = soap.Price. No brackets, no method names.

From inside, every read runs Get and every write runs Set(value), where your logic stands guard: our Set refuses negatives, so soap.Price = -5D leaves 35 in place.

Java made you write getPrice()/setPrice() and made callers remember to use them. VB bakes the doorway into the syntax. For no-logic cases, one line suffices: Public Property Name As String (an auto-property).

Quiz

With the listing's guard, what does soap.Price hold after: soap.Price = 35D followed by soap.Price = -5D?

  1. -5: the last assignment always wins
  2. 35: the Set block ran, and its guard refused the negative value
  3. 0: rejected assignments reset the backing field
  4. Compile error: you cannot assign to a property
Show the answer

35: the Set block ran, and its guard refused the negative value

An assignment to a property is a CALL to its Set block with value = -5; the If chose to do nothing, so _price kept 35. That interception is the entire point of properties: option A is true of raw public fields, which is precisely why _price is Private with the property standing in front. Option C invents punishment logic nobody wrote. Option D is backwards: assignability with control is the feature. Field-like outside, method-like inside: hold both halves of that sentence.

Think first

Why not just Public Price As Decimal?

A classmate says: skip the ceremony, make the field public, save 8 lines. Give 2 concrete reasons the property earns its lines, before tapping.

Show the answer

1: Validation has an address. A public field accepts -5 from any line in the program; the property's Set is the ONE gate every write passes, so no-negative-prices is enforceable at all. 2: You can change the inside without breaking the outside. If price later comes from a discount rule or a database read, Get's body changes and every caller compiles untouched; with a public field, that migration rewrites the whole program. This is encapsulation (2 lessons ahead) wearing its VB uniform: same argument you made for private + getters in BCA403, minus the clunky method calls.

Theory

Events: you have been using them all unit

Every Handles btnAdd.Click you wrote in Unit 3 was you SUBSCRIBING to an event someone else declared. Classes you write can declare their own:

Public Event LowStock(ByVal itemName As String)

and fire it when the moment comes:

If qty < 5 Then RaiseEvent LowStock(Name)

Any form can then handle it (AddHandler wires it in code) and, say, flash a reorder label. Declare with Event, fire with RaiseEvent, listen with Handles/AddHandler: the Button was never magic, just this pattern shipped in the Toolbox.

Watch out

Three member mix-ups

Sub New is the only constructor spelling: a Sub named Item inside class Item is an ordinary method, the same imposter trap as BCA403's void Book().

Set runs even when it refuses: silence is not failure; check the backing field, not your assumption.

Do not count on Finalize: it may run late or (at process exit) effectively not at all; anything that must close promptly (files, connections: Unit 5) gets an explicit close call, not a hope.

Theory

The bill becomes objects

ShopKeeper's redesign now writes itself: an Item class (this listing), a Bill class holding an ArrayList of Items with an AddItem method and a Total function, and the DataGrid displaying what the OBJECTS say, instead of being the only place truth lives. Screens display; classes know. The next 3 lessons tune the class machinery: who may touch what (access specifiers), and the family keywords Me, MyBase, MyClass where Java said this and super.

Summary

Key takeaways

  • Class ... End Class packs fields, Sub New constructors, methods, properties and events.
  • Construction: Dim x As New Item(...) runs Sub New; defining one removes the free no-arg constructor.
  • No destructors: the GC reclaims objects; Finalize may run, non-deterministically.
  • Property = Private backing field + Get/Set doorway: field syntax outside, guard logic inside.
  • A refusing Set leaves the old value: 40, then 35, then -5 refused keeps 35; LineTotal(3) = 105.
  • Events: declare with Event, fire with RaiseEvent, subscribe with Handles/AddHandler: Unit 3's Click demystified.
  • Memory hook: properties are fields with a doorman.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Object Oriented Programming

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Creating Classes, Object Construction & Destruction: Properties, Methods, Events · .NET Programming · Gri-Learn