100 likes | 250 Vues
More about classes and objects. Classes in Visual Basic.NET. We have seen. Basics of OOP terminology Object Class Method Overloading Overriding Basics of OOP concepts Abstraction Polymorphism Encapsulation Inheritance How to draw class diagrams. Shape. x, y : Integer.
E N D
More about classes and objects Classes in Visual Basic.NET
We have seen ... • Basics of OOP terminology • Object • Class • Method • Overloading • Overriding • Basics of OOP concepts • Abstraction • Polymorphism • Encapsulation • Inheritance • How to draw class diagrams
Shape x, y : Integer draw() : String Rectangle Circle r : Integer h, w : Integer Shape, Circle and Rectangle
Creating classes in VB.NET • Classes are written in files, in a similar way than forms. • They are added using the Add class... item in the Project menu. • Involves ... • setting up the variables • implementing a constructor • implementing the methods required
Code for Shape Public Class Shape Protected x, y As Integer Public Sub New() x = 12 y = 30 End Sub Public Function draw() draw = "I am a nice shape" End Function End Class
Abstract classes • Cannot be instantiated • Only classes that extend them can be instantiated • Used as holders for their subclasses • VB.NET uses keyword "MustInherit" • Public MustInherit Class Shape
Creating subclasses • Two options: • New file (through Add class...) • Same file • Subclasses might hold variables of their own • VB.NET uses keyword "Inherits" • Public Class Circle Inherits Shape
Overriding methods • A subclass can redefine methods that appear in its parent • Circle can give a new implementation to inherited method draw() • VB.NET uses the keyword "Overrides" • Public Overrides Function draw()
Abstract methods • Sometimes the parent class just "mentions" a method, without providing an implementation • VB.NET uses keyword "MustOverride" • Any class with at least one abstract method must be declared abstract • It is a good idea to make the method draw() in Shape abstract
Abstract Shape Public MustInherit Class Shape Protected x, y As Integer Public Sub New() x = 12 y = 42 End Sub Public MustOverride Function draw() End Class