locked
I'm working on some more practice programs from my book.

    Question

  • I'm still learning classes and inheritance so I apologize for so many questions.  I guess I'm just supposed to have this many classes to satisfy the practice program because to me it seems like you could do this easier without all the classes?  So I'm just not sure what goes where and why.  I'll try to type all this up in notepad the way the book says so it looks right here.

    Create a set of classes that use inheritance according to the following hierarchy:


             SHAPE
           /            \
          /              \
    CIRCLE      SQUARE
      |
      |
    CYLINDER


    Please note that your Shape class should contain only the following:

        * an x value � this is the horizontal location of the Shape
        * a y value � this is the vertical location of the Shape
        * a way to get and set each of these fields
        * a constructor that takes initial values for x and y
        * a ToString method that will return a description of the Shape as a String.

    NOTE: At no time in this Project will you be writing code to draw any of the Shapes.  Instead, you'll be using your classes to represent the Shape.

    Once your Shape class is written, you'll write the Circle, Cylinder and Square classes, inheriting from the appropriate classes according to the diagram.  Be sure that each class contains appropriate instance variables (based on the class type) and methods (a way to get and set each variable, appropriate constructors, a way to calculate area or volume and a ToString method).

    When you have all of your classes complete, write a console application that creates a single array of Shape objects.  Store at least two objects of type Circle, two of Cylinder and two of Square in your array.  Be sure to prompt your user for the values of the variables.  Once all objects have been created, use a loop to go through the array and print a description of each object by calling its ToString method.

    Although not required to look this way, your program output might look like:

        Please enter the x location of the first circle: 1
        Please enter the y location of the first circle: 2
        Please enter the radius of the first circle: 3

        Please enter the x location of the second circle: 4
        Please enter the y location of the second circle: 5
        Please enter the radius of the second circle: 6

        Please enter the x location of the first cylinder: 7
        Please enter the y location of the first cylinder: 8
        Please enter the radius of the first cylinder: 9
        Please enter the height of the first cylinder: 10

        Please enter the x location of the second cylinder: 11
        Please enter the y location of the second cylinder: 12
        Please enter the radius of the second cylinder: 13
        Please enter the height of the second cylinder: 14

        Please enter the x location of the first square: 15
        Please enter the y location of the first square: 16
        Please enter the length of the first square: 17

        Please enter the x location of the second square: 18
        Please enter the y location of the second square: 19
        Please enter the length of the second square: 20

        Your shapes are:
        Circle at (1, 2) with radius 3 has area 28.26
        Circle at (4, 5) with radius 6 has area 113.04
        Cylinder at (7, 8) with radius 9, height 10 has volume 2543.4
        Cylinder at (11, 12) with radius 13, height 14 has volume 7429.24
        Square at (15, 16) with length 17 has area 289
        Square at (18, 19) with length 20 has area 400
        Press any key to continue
    • Edited by JynxRD Friday, November 14, 2008 12:19 AM
    Thursday, November 13, 2008 1:12 AM

Answers

  • *** For case of your solution moving faster then me between bed and desk, and also for better orientation:
    1. complete your I/O transfer from consumer routine to class bussiness, so that "Dim c1 As New Circle("first") : c.Input() : c.Output()" will procede everything needed to perform for c1 in Sub Main() in original assignment.
    2. try to think out some changes for 1) so that you would e.g. passed a parameter to constructor, which would cause Me.Input() call immediatelly after MyBase.New() - in this case you use If parameter = ... Else ... End If - maybe parameter of boolean or byte TYPE; or for example which would replaced Output() method with overriden ToString() function...
    3. try to describe what is difference between CLASS and TYPE (e.g. Integer), try to squeeze some initial opinion or supposition from how looks Sub Main now (what disappeard and what appeared? Where is currenty each shape's name stored? How could it be accessed? Is it more micro-operations to access c1.width than to access width from inside of c1?
      (Tip: do your own research on VARIABLES and POINTERS, supposing Integer to be somehow different to Shape ... does Integer also have Instance and Constructor?)
    4. try to describe what is difference between unset Integer, and uninitialized Class
      (Tip: Error: "object not set to an instance" when you forget to call constructor of shape and you are trying to obtain value of some property. Just use this code for this research "Dim i As Integer : MsgBox i.ToString || Dim a As Square : MsgBox a.xlocation" -- this is related to pt 3)
    5. try to modify shape class and also square class for: square provides only Width to end user, or square provides both, but when setting Width Height is also set and reversely.
    6. try to modify circle class: so it provides only Diameter and/or Radius, while these both are only exposing Width. Don't expose Height, and try to find good compromise for 5 & 6 request, while both require some particular changes in base class (using Protected-Public method to expose or not base method/property in derived class)
    7. Ace of interest: do you think you would be able to provide two Square properties from Circle, which would, when used to SET, modify its Width (radius & diameter respectively) computing it from value set? In detail you would provided inside Square of Circle on GET, and you would accept such rectangle via SET as radius modification? Is there some way to reuse inside square computations for second, similar property outside square?
    8. Ace of interest: do you think you would be able to create 3D cylinder reusing (without its modification) current 2D Shape or Circle? You musn't inherit it - instead you can inherit base shape3D from shape and then inherit circle3D from it and cylinder3D from that. Can you somehow use instance of cylinder in cylinder3D?
    9. Ace of interest: after this all, check out your concept, are there some else conceptual mistakes as Michal pointed out? Do they have something common? Can you really take them as mistake, when you read my rest off link (while americans would just inherit person from address..)?
    10. Try to find some way how to distribute functions in hierarchy: can you also split some functions to functions as shown in Ball of Material? Can you move some of resulting functions to base so that MovingBall - Ball functional division appears?
    11. Try to decide if you just have closed this chapter, or if you need to practice and understand something more deeply (Class, Instance, Constructor, Providing / Exposing, Sense in dividing of bussiness, Sense in depicting a reality, MustInherit & MustOverride, Relation between Object and every class - reason of Overrides ToString, Private & Public, Protected & Public, Reasons of property & metaphores to it, Providing constructor, relation of Class and DATA, difference between Structure and Class ... probably I missed something? Classes WithEvents? Reflection?) ... or just find your own focus of interest :)
    12. If you will not run away lately, I would welcomed your code tuned up to perfection and showing all 1-10 points of knowledge about classes. I am pretty sure, that you are able to manifest such code, with no usage of internet, book except for 3 & 4. But also I recommend you to use it for any point if you are just not sure of some keyword, and for any case post your question here. This is not school paper ;) And I am pretty confusing teacher, at least! You have ten minutes. *
    13. Exit>_ Error: Object not set set to instance while trying (13).Exit

     

    ***learn to be the only one who govern coding priorities, don't let yourself confuse, try to preserve focus, do your own task list (or research mission plan :). Learn how to react if you are in some depth and you find some problem of its own depth, confusing you else with bulb-head problematic: is putting new problem to task list only solution? How to find out if new task can later, taken from task list, destroy your previous deep modifications? Etc... but mainly basic focus preserving and being "above" all problems outside focus is sufficient. Also even if you don't understand a thing, you should lead your helper to notice your focus or also interest...

    * four seconds to select your starting point from [1..10,13], and ten minutes to restart computer after microsoft update of ms office :) - ok I am really not prophet, but I am sure you can be much more proud of yourself after you get your book tuned.

    ///See you later, I am going to perform sleep cycle which takes usually 12 hours... uf, how would you implement "Fixation of iconic data using rotating windows"? Or what could it sign? I have bit deformed dreams probably :) But I would be really curious if you could propose e.g. some placement of such function? Does this ET use for reading .txt files, or it is only his scandisk? Peh. :P

    Regards, Matej

    • Edited by konikula Friday, November 14, 2008 7:21 AM context extension to pt3
    • Marked as answer by Xingwei Hu Wednesday, November 19, 2008 6:09 AM
    Friday, November 14, 2008 7:07 AM

All replies

  • So what is actually your question? :) Do you want us to write the solution for you or do you have some more specific question? (It seems to be a pretty easy practice problem so it won't be much trouble for me to show you the complete solution, I'm not sure if this is what you want though.)
    Thursday, November 13, 2008 11:30 AM
  • Try to use your knowledges from Classes and Inheritance princliples, namely Circle-Point sample. After you get Shape - Circle try to code Cylinder and paste your scratch, we will surely* check your solution and help you more concretely to get the way in.

    Regards, Matt
    • Edited by konikula Thursday, November 13, 2008 7:34 PM * you can use some pseudo code now, later we can fill functions or properties with code etc..
    Thursday, November 13, 2008 7:32 PM
  • Well, I'm not one who likes things done for me, but in this case its not like its graded so it doesn't matter.  I guess maybe you can just get me started or post whatever you want.  I learn mostly from looking at source anyways, and since I'm teaching myself it really helps to follow the code and see why and how it works.  The internet and my book are my only resources lol so I love you guys!  I'll look at website after website before I even post anything here.  I use this as my last resort.
    Thursday, November 13, 2008 8:33 PM
  • Oh and konikula, that is the first place I went actually but I wasn't sure how to apply that to mine.  I see the basic idea of it but once again I'm probably making things harder than they actually are.
    Thursday, November 13, 2008 8:34 PM
  • :) that's just reason for me to ask you for some scratches for us to check and lead you from, to final solution. I am sure you are not sure. But this "not sure" and its impact to your scratch is just what we need to lead you to grow more personal insight to problematic... If I just posted you 1-2-3 inheriting code, ignoring you can try to synthesize it from 1-2, you could miss some good research to theme :) Just give it try, it is also very probable you will scratch perfect 1-2-3 solution, which I only propose as answer :) I hope there is noone who would do any negative remarks to your scratch, except me :D
    Thursday, November 13, 2008 8:49 PM
  • I'm so proud of myself!  I want you to look this over before I get to ahead of myself and make sure I'm doing all this right.  Yes it works but does it satisfy the instructions?  Now I assume since it was 2 sets of each as in the instructions that I just need to double everything?  Or do I have to double it and override my functions?  I'm not sure from here.  Here is all I ha

     
    1Module Module1 
    2 
    3    Sub Main() 
    4 
    5        Dim r As New Circle() 
    6        Console.Write("Please enter the x location of the first circle: "
    7        r.xlocation = CInt(Console.ReadLine) 
    8        Console.Write("Please enter the y location of the first circle: "
    9        r.ylocation = CInt(Console.ReadLine) 
    10        Console.Write("Please enter the radius of the first circle: "
    11        r.radius = CInt(Console.ReadLine) 
    12 
    13        Dim s As New Cylinder() 
    14        Console.Write("Please enter the x location of the first Cylinder: "
    15        s.xlocation = CInt(Console.ReadLine) 
    16        Console.Write("Please enter the y location of the first Cylinder: "
    17        s.ylocation = CInt(Console.ReadLine) 
    18        Console.Write("Please enter the radius of the first Cylinder: "
    19        s.radius = CInt(Console.ReadLine) 
    20        Console.Write("Please enter the height of the first Cylinder: "
    21        s.height = CInt(Console.ReadLine) 
    22 
    23        Dim c As New Square() 
    24        Console.Write("Please enter the x location of the first Square: "
    25        c.xlocation = CInt(Console.ReadLine) 
    26        Console.Write("Please enter the y location of the first Square: "
    27        c.ylocation = CInt(Console.ReadLine) 
    28        Console.Write("Please enter the length of the first Square: "
    29        c.length = CInt(Console.ReadLine) 
    30 
    31        Console.WriteLine("Circle at ({0} {1}) with radius {2} has area {3} ", r.xlocation, r.ylocation, r.radius, r.Area) 
    32        Console.WriteLine("Cylinder at ({0} {1}) with radius {2}, height {3} has volume {4} ", s.xlocation, s.ylocation, s.radius, s.height, s.Volume) 
    33        Console.WriteLine("Square at ({0} {1}) with length {2} has area {3} ", c.xlocation, c.ylocation, c.length, c.Area) 
    34 
    35        Console.WriteLine("Press escape to exit"
    36        Do : Loop Until Console.ReadKey().Key = ConsoleKey.Escape 
    37 
    38    End Sub 
    39 
    40End Module 



    1Public MustInherit Class Shape 
    2 
    3    Dim l, b, r, h, le As Single 
    4 
    5    Property xlocation() 
    6        Get 
    7            Return l 
    8        End Get 
    9        Set(ByVal Value) 
    10            l = Value 
    11        End Set 
    12    End Property 
    13 
    14    Property ylocation() 
    15        Get 
    16            Return b 
    17        End Get 
    18        Set(ByVal Value) 
    19            b = Value 
    20        End Set 
    21    End Property 
    22 
    23    Property radius() 
    24        Get 
    25            Return r 
    26        End Get 
    27        Set(ByVal Value) 
    28            r = Value 
    29        End Set 
    30    End Property 
    31 
    32    Property height() 
    33        Get 
    34            Return h 
    35        End Get 
    36        Set(ByVal Value) 
    37            h = Value 
    38        End Set 
    39    End Property 
    40 
    41    Property length() 
    42        Get 
    43            Return le 
    44        End Get 
    45        Set(ByVal Value) 
    46            le = Value 
    47        End Set 
    48    End Property 
    49 
    50End Class 

    1Public Class Square 
    2    Inherits Shape 
    3    Public Function Area() As Single 
    4        Return MyBase.length * MyBase.length 
    5    End Function 
    6End Class 



    1Public NotInheritable Class Cylinder 
    2    Inherits Circle 
    3    Public Function Volume() As Single 
    4        Return (MyBase.height * Math.PI) * (MyBase.radius * MyBase.radius) 
    5    End Function 
    6End Class 



    1Public Class Circle 
    2    Inherits Shape 
    3    Public Function Area() As Single 
    4        Return MyBase.radius * MyBase.radius * Math.PI 
    5    End Function 
    6End Class 

    Thursday, November 13, 2008 11:32 PM
  • !!! warning this is written before I read || noticed your last post...
     
    Yes you can write it as you want: simple mathematic operation looks in VB (as in much of other languages) same as it looks at school on paper: so that if talking about h * pi * r2 you musn't even () * () it. You only write h * PI * r ^ 2 (where ^2 is only difference to school formula, because upper inscription of square of 2 is not possible - formatting does not have any role in any programming language). Few years ago you would write r * r instead of r ^ 2, because it was possibly optimisation for processor. Todays you can still use r + r instead r * 2, it is of course partial optimisation...

    What is much important for you is now, that you can divide whole h * PI * r^2 expression into yours three classes, each of them computes a part, which second class won't confuse with... As with square & cube ... where square offers property "area" (and computes Me.Width * Me.Width for it) and cube does not confuse with computing "area" again... it uses property of base class, and so it computes Me.Area * Me.Width only ... You can imagine much more difficult inheritance case, where you bypass huge coding by such reusing of base function:

    1 Class Ball  
    2  Inherits Circle 'what provided us Radius value  
    3    
    4  Public Material As Physics.Material  
    5  
    6  Public ReadOnly Property Volume#
    7  ### Return (4 / 3) * PI * Me.Radius ^ 3  
    8  
    9  Public ReadOnly Property Weight#
    10  ### Return Me.Volume * Me.Material.Density  
    11  
    12  Public ReadOnly Property RotationEnergy(Speed#)
    13  ### Return 0.5 * Me.Weight * Speed^2  
    14  
    15 End Class 
    16  
    17 'and now you bypass computations signed in class Ball using just property RotationEnergy  
    18 Class MovingBall  
    19 Inherits Ball  
    20    
    21  Public MovementSpeed#  
    22    
    23  Public ReadOnly Property MovementEnergy#()
    24  ### Return 0.5 * Me.Weight * MovementSpeed ^ 2  
    25  
    26  Public ReadOnly Property Energy(rotation#)
    27  ### Return Me.RotationEnergy(rotation) + MovementEnergy()  
    28 End Class 

    Next profit of such division of code as between functions (RE (= W (= V), as between
    inherited classes (MB.E (= B.RE), is that you can debug only partial calculations, and you are not confused with values which would be exposed in contrary: e.g. you really do not need to confuse yourself with Radius while computing Weight, and it is really easy to check all computations against your schoolbook of physics :)

    Note: if you would test to compute Energy of rotating and also moving Ball with sample classes, you would find out, that it is not computing correctly! In debug, first what you would check is function Energy(rotation#), and you would found in your schoolbook, that kinetic energy of moving and also rotating object is not such simple as E(R) + E(M) ... so it spared your time with checking each used function, or in worse case, checking such physical code:

    1 Function Energy#(RotationSpeed#)  
    2  Dim Weight# = ((4 / 3) * PI * Me.Radius ^ 3) * Me.Material.Density 'compute weight from volume  
    3  Dim Ret# = Weight * 0.5 * RotationSpeed ^ 2  
    4  Return Ret + 0.5 * Me.Weight * MovementSpeed ^ 2 'add movement energy to result  
    5 End Function 

    So now you can inspire :) Also, really, main profit of using Classes and Inheriting Classes is such division of code... Objects expose only such properties and methods, which in normal world belong to these objects. But this is not so far from dividing function to functions (line 13). Main difference of these two recyclations is, that Class also holds some values, and pools Methods ... what is quite far from what you can do dividing function to functions. Inheriting then gives next dimension to code division: you divide mechanisms and data, using kind of morph hierarchy. In fact there is no other sense of using classes, than what our Chocolate & Coffein programmer told: "If I click my data, I get all functions, methods, properties and enveloped variables which I could need to work with this data..!". And for inheriting, lets say you got kind of "code folders" - if you take MovingBall, you also took Ball...

    :) I hope I didn't confused you with this...stay focused to your mathematical expression

    regards, Matej
    • Edited by konikula Friday, November 14, 2008 1:39 AM oh, grammary, 3-
    Friday, November 14, 2008 12:39 AM
  • Ok, I read a part (in order to be a bit sequentious). If you would mind, you can try, how to ensure, that Consumer programmer of Square will not set it to be rectangle? (Please let some formula division for finalizing - after we squeeze your code to be perfect - in reverse it would be more complicated work for you to tune it up).

    P.S:Seems as quite good work now (e.g. NotInheritable used perfectly).
    • Edited by konikula Friday, November 14, 2008 12:50 AM
    Friday, November 14, 2008 12:49 AM
  • Yep, you lost me.  You write about this like a philosopher!  But I enjoyed reading it.  With that said, I 'm not sure if I was able to gather the answer to my question (maybe that's the part you saw after this post) as to if my current code is correct or if I should be using some type of overriding?  And how I should go about duplicating everything since I need 2 circles, 2 cylinders, 2 squares.
    Friday, November 14, 2008 12:50 AM
  •  I am glad that you enjoyed it :) It is positive mark for me, and also for you - if I enjoy something, I am sure I will be good in it :) May I await your ideas about my Square x Rectangle securising? (I will try to get your Yep message under control ... I am quite confused, but let me read it for while.. :)
    • Edited by konikula Friday, November 14, 2008 12:57 AM
    Friday, November 14, 2008 12:54 AM
  • Well, I have

    1        Dim r As New Circle() 
    2        Console.Write("Please enter the x location of the first circle: "
    3        r.xlocation = CInt(Console.ReadLine) 
    4        Console.Write("Please enter the y location of the first circle: "
    5        r.ylocation = CInt(Console.ReadLine) 
    6        Console.Write("Please enter the radius of the first circle: "
    7        r.radius = CInt(Console.ReadLine) 

    But in order to also do the second circle, how would I do that?  Would I just create basically a duplicate of everything?  Such as with the circle class, would I have area and area2 ?  Or is this where the overriding comes in?  I'm not sure how to do it in order to have Second Circle, Second Cylinder, Second Square.

    Friday, November 14, 2008 1:17 AM
  • Note to your questions of doubling. I have a real reason to be confused. You are about to double something in your classes code, or 'override' it, because in that book is every object double on input and output (Input Square1, Input Square2, Output Square1, Output Square2)? If you are confused right about this part of assignment, lets forget about it :) It is just on you to decide if doubling Console.Write and Console.Readline lines, with replacing "first" to "second" has some sense, relevant to thema :) I would call this doubling of I/O in assignment as personal pleasure of writer of that book, personally :) ... if you want to continue with Override and its usage, lets delay it for next thread...? (while you can still tune your code in this thread to perfeccy, in order to get your knowledge of Protected And Private statement deeper..)
    Friday, November 14, 2008 1:17 AM
  • Well I get that I can simply double the input/output in the main module but what do I do to each class in order for it to hold 2 values for each?  How do I do multiple input/output for circle using the circle class?  Do I have to create 2 area functions or is there a more efficient way?


    1Public Class Circle 
    2    Inherits Shape 
    3    Public Function Area() As Single 
    4        Return MyBase.radius * MyBase.radius * Math.PI 
    5    End Function 
    6End Class 


    Friday, November 14, 2008 1:22 AM
  • Or next way to do this, staying on assignment: if you would just created Sub Input and Sub Output in each class, you would then replaced whole Sub Main code with something much shorter and Perfectionistic.
    1 Sub Main ()  
    2  Dim c1 As New Cylinder()  
    3  c1.Input()  
    4  Dim c2 As New Cylinder() : c2.Input  
    5  ...  
    6  c1.Output() : c2.Output()  
    7  s1.Output() : s2.Output()  
    8  ...  
    9 End Sub 

    Eh?
    Friday, November 14, 2008 1:24 AM
  •  To answer your latest post: I hope you will research your own answer after modification of Sub Main I proposed... Also this shows, that your book somehow confused you: you are now able to Inherit, but you really don't know what Class is? You may find your answers after this modification with look at sub Main.. (I shamely also didn't imagined you are able to learn Inherit without knowing practical sense of class yet, sorry for this - lets see how fast you will learn bypassed knowledge, I would guess very fast). Notable keywords for later Sub Main() research: Class, Instance of class, Constructor of instance;
    • Edited by konikula Friday, November 14, 2008 1:41 AM temporarily blackenredded
    Friday, November 14, 2008 1:32 AM
  • Ok I see what you mean by making Sub Main better.  But in your exampling, Class Cylinder would still need Sub input() and Sub input2() right?  Because Sub Input() will console.write asking you to enter info using the text "First" and then Sub input2() would ask the same question but use the text "Second".   Right?
    Friday, November 14, 2008 1:57 AM
  • I'm getting it.  Another question though.

    Since Class Shape has the values for xlocation and ylocation  

    and Class Circle inherits Class Shape - Do you even have to put MyBase.xlocation  and MyBase.ylocation - Simply typing xlocation and ylocation still works right since its inheriting those values from Class Shape I don't have to tell it that its from the base class inless I also have a different xlocation within Class Circle then I would need MyBase.xlocation and Me.xlocation

    Am I correct in my thinking?
    Friday, November 14, 2008 2:16 AM
  • !!! warning this is written before I read || noticed your last post...
     
    Ok, lets tell you can add Public Dim Name As String to each class. Then you will call Dim c1 As New Cylinder("first") from sub main? In constructor you will take CallMeJack$ argument and proceed Me.Name = CallMeJack. Then in Input and Output methods use concatenating of strings to modify printed text for each called shape... (tip: e.g. Dim someText$ = "Help me " & myFriend & " I cannot swim" ... which preceeded by myFriend = "Matej" sets someText to concrete sense, depending on who is actually with you taking philosopical walk around lake :)

    Also you can be very rigid, and force consumer of base Shape class to call each shape somehow: if you just start with Shape, you will see that all derived classes (~ inherited) will highlight something in themselves as error. (Just because you forbid empty constructor in Class Shape, and offer only Named constructor)

    Do you need code for rigid constructor?
    • Edited by konikula Friday, November 14, 2008 2:27 AM
    Friday, November 14, 2008 2:26 AM
  • Right.  So currently Sub Main() :

    1        Dim r As New Circle() 
    2        r.input() 
    3        Dim r2 As New Circle() 
    4        r2.input2() 

    And then Class Circle :

    1    Sub input() 
    2        Console.Write("Please enter the x location of the first circle: "
    3        xlocation = CInt(Console.ReadLine) 
    4        Console.Write("Please enter the y location of the first circle: "
    5        ylocation = CInt(Console.ReadLine) 
    6        Console.Write("Please enter the radius of the first circle: "
    7        radius = CInt(Console.ReadLine) 
    8    End Sub 
    9    Sub input2() 
    10        Console.Write("Please enter the x location of the second circle: "
    11        xlocation = CInt(Console.ReadLine) 
    12        Console.Write("Please enter the y location of the second circle: "
    13        ylocation = CInt(Console.ReadLine) 
    14        Console.Write("Please enter the radius of the second circle: "
    15        radius = CInt(Console.ReadLine) 
    16    End Sub 

    Can I however utilize only Sub Input() to ask for both "first circle" and "second" circle without having to rely upon Sub Input2()
    Friday, November 14, 2008 2:34 AM
  • Using MyBase instead of Me is offten only your selection, to have compact code, you sometimes need to write MyBase.xlocation to capitalize its "source". But also remember, that that is really no source, as you can't consider you to have source of legs in your father :D. Let's try rigid constructor, it will show you that here is also some case, where MyBase is necessary inscription. After we have named objects, you can complete I/O methods, fix Sub Main and check out what you learned from it all. Please now be more focused. You can see there is big recursive bubble rising from your questions and notes. If you let it grow, you will be confused to death. So now just focus on rigid named constructors. Ask for anything you don't know. :)
    Friday, November 14, 2008 2:35 AM
  • To your latest code sample. Please move to rigid named constructor before you implement such code in all classes :)!! I am warning you: if you will not move before, you will then delete half of code with frustrated smile! (just try to go with my latest paragraphed and bit longer suggestion with Do you need at end)
    • Edited by konikula Friday, November 14, 2008 2:40 AM
    Friday, November 14, 2008 2:37 AM
  • Just ask anything you need to understand and code my latest three posts. (except this)
    • Edited by konikula Friday, November 14, 2008 2:43 AM
    Friday, November 14, 2008 2:42 AM
  • "Do you need code for rigid constructor?"

    Yea I guess I do because I'm not sure what you want me to change.
    Friday, November 14, 2008 2:48 AM
  • Ok. Just for example (sorry for I am explaining something I wanted you to research yourself, de facto :P but also I know, that learning of interesting thing with bulb-head from it is wrong learning, so this reduction of your steps is needed)

    1 MustInherit Class Planet 'cannot exist except its derivation to concrete planet  
    2  Public Name As String 
    3  Private Sub New()  
    4   'do nothing here ...  
    5  End Sub 
    6    
    7  Protected Sub New(CallMeJack$)  
    8   Me.Name = CallMeJack  
    9  End Sub 
    10 End Class 
    11  
    12 Class Earth  
    13  Sub New() 'notice that without any constructor Earth is colored blue with message  
    14   MyBase.New("Earth"'and also notice, that you MUST call MyBase.New with name  
    15  End Sub 
    16 End Class 
    17  
    18 'or  
    19  
    20 NotInheritable Class SunSystemPlanet  
    21  Inherits Planet  
    22  Sub New(Name$)  
    23   MyBase.New(Name)  
    24  End Sub 
    25 End Class 

    what will interest you is SunSystemPlanet ... apply this schema to your code first... after you have named shapes, you maybe get what to do with Input1 and Input2 :)
    Friday, November 14, 2008 3:00 AM
  • That's why I called you being rigid when coding zero-arity constructor as Private and PROVIDE only named constructor to derived classes: it in fact disables consumer of Base class to create unnamed planets... And that's why I allowed myself to call this principle of doing MustInherit Class principle of "Rigid named constructor" (maybe it could sound better as Rigid callMeJack class? :)
    • Edited by konikula Friday, November 14, 2008 3:07 AM smile
    • Proposed as answer by konikula Friday, November 14, 2008 3:19 AM
    Friday, November 14, 2008 3:05 AM
  • Eh, sorry, I mistakenly mark previous post as answer :)

    For resting off you can take this discussion to oop -
    Friday, November 14, 2008 3:21 AM
  • OK I haven't read the whole conversation so don't yell at me if this has been already covered :).

    I don't think you're doing this quite right. Your shape class has properties such as radius, length, height etc. I don't think these properties logically belong there. This way for example will Square also have radius and height which doesn't make any sense. Shape should only define properties which are common to all the shapes - in this example xposition and yposition. (By the way it's a good practice to capitalize public members e.g. XPostion.)

    If you read carefully your problem statement, it even says that Shape should only contain x and y values, not radius length or height.

    Here's how would I implement Shape and Circle, I'm sure you'll be able to figure out the rest:

        Public MustInherit Class Shape 
            Private x, y As Double 
     
            Public Sub New() 
     
            End Sub 
     
            Public Sub New(ByVal x As DoubleByVal y As Double
                XLocation = x 
                YLocation = y 
            End Sub 
     
            Public Property XLocation() As Double 
                Get 
                    Return x 
                End Get 
                Set(ByVal value As Double
                    x = value 
                End Set 
            End Property 
     
            Public Property YLocation() As Double 
                Get 
                    Return y 
                End Get 
                Set(ByVal value As Double
                    y = value 
                End Set 
            End Property 
        End Class 
     

        Public Class Circle 
            Inherits Shape 
     
            Public Sub New() 
                MyBase.New() 
            End Sub 
     
            Public Sub New(ByVal x As DoubleByVal y As Double
                MyBase.new(x, y) 
            End Sub 
     
            Private r As Double 
     
            Public Property Radius() As Double 
                Get 
                    Return r 
                End Get 
                Set(ByVal value As Double
                    r = value 
                End Set 
            End Property 
     
            Public ReadOnly Property Area() As Double 
                Get 
                    Return Math.PI * Radius * Radius 
                End Get 
            End Property 
     
            Public Overrides Function ToString() As String 
                Return String.Format("Circle at ({0}, {1}) with radius {2} has area {3}", XLocation, YLocation, Radius, Area) 
            End Function 
     
        End Class 
     

    Your main method should then according to the problem statement store the shapes in an array of shapes so it should look something like this:

        Sub Main() 
            Dim shapes(5) As Shape 
     
            Dim circle1 As New Circle() 
            Console.Write("Please enter the x location of the first circle: "
            circle1.XLocation = CDbl(Console.ReadLine()) 
            Console.Write("Please enter the y location of the first circle: "
            circle1.YLocation = CDbl(Console.ReadLine()) 
            Console.Write("Please enter the radius of the first circle: "
            circle1.Radius = CDbl(Console.ReadLine()) 
            shapes(0) = circle1 
     
            '... 
     
            For i As Integer = 0 To 5 
                Console.WriteLine(shapes(i).ToString) 
            Next 
        End Sub 
     

    Friday, November 14, 2008 3:26 AM
  • Thanks for valuable remark, we could easily miss such misconception after enchancing style of I/O :)

    I would recommend you, Jinx, to only notice this and repair it after you understand class and instance concepts (after your Sub Main() research), while you will also divide functions as in physics example manner - it will be good to do this together.
    Friday, November 14, 2008 3:35 AM
  • Good remark to discussion with Michal: I suppose every shape has At Least Length. So it could be something like preserving Width and Height, but computing Radius in Circle as half of Width, while protecting Height from exposing in Circle, and exposing Width (length) thru Diameter and also thru Radius?

    this is also to the bottom of research mission buffer... just don't confuse, there is plenty of time, so you musn't think about "conception bugs" while you are busy with Instance and Class or constructors and test sub main... even such mix is possibly not natural warp of increasing your oop knowledge, god knows :P
    • Edited by konikula Friday, November 14, 2008 3:50 AM
    Friday, November 14, 2008 3:49 AM
  • Konikula : I'm still trying to figure out what to do with what you gave me above.

    Michal :  Why does :

    Console.WriteLine(shapes(i).ToString)  


    Give this error?  Object reference not set to an instance of an object.
    Friday, November 14, 2008 3:52 AM
  • In my example I only set

    shapes(0) = circle1

    and then wrote ... to indicate that you should fill in the rest of the array with some other shapes. So in the code I posted, shapes(1), shapes(2) etc contain Nothing and therefore calling shapes(1).ToString() gives an error. So either change the loop to For i = 0 To 0 (well that doesn't really make much of a loop :D) or fill the rest of the shapes array with some shapes ;):

    Dim circle2 As New Circle()
    shapes(1) = circle2

    etc...
    Friday, November 14, 2008 3:56 AM
  • Ok. Do you remember as we printed some info for Point or Rectangle using Overrides ToString? Why just not to use such mechanism for Output function? (just the way goods of ToString worked with X and Y). Just don't make such horrible propositions. It is easy, when all of your shapes have Name... I would see it as you only Console.Write(myCylinder.Output()) And it would say "Your first cylinder is on your head" and for mySecondCylinder.Input it would tell "You second cilinder is on peg do you need to switch it with that on your head [1,2]?:" :)

    Remember you called* them first and second in Initialization || Instantisation as volks would oppose ... notice that Sub New is constructor, and it is called (used) to construct an instance of class. So that you initialize an instance using declaration with New keyword (in short instantiate), and it uses constructor method (sub new): in case you have more constructors, it uses constructor of same arity (also of same type of arguments if arity is same in two constructors)

    *So that your Input() already knows myBase.Name in both cases... what can reduce......... :D
    • Edited by konikula Friday, November 14, 2008 4:30 AM grammar 2-: an instance not a
    Friday, November 14, 2008 4:25 AM
  • *** For case of your solution moving faster then me between bed and desk, and also for better orientation:
    1. complete your I/O transfer from consumer routine to class bussiness, so that "Dim c1 As New Circle("first") : c.Input() : c.Output()" will procede everything needed to perform for c1 in Sub Main() in original assignment.
    2. try to think out some changes for 1) so that you would e.g. passed a parameter to constructor, which would cause Me.Input() call immediatelly after MyBase.New() - in this case you use If parameter = ... Else ... End If - maybe parameter of boolean or byte TYPE; or for example which would replaced Output() method with overriden ToString() function...
    3. try to describe what is difference between CLASS and TYPE (e.g. Integer), try to squeeze some initial opinion or supposition from how looks Sub Main now (what disappeard and what appeared? Where is currenty each shape's name stored? How could it be accessed? Is it more micro-operations to access c1.width than to access width from inside of c1?
      (Tip: do your own research on VARIABLES and POINTERS, supposing Integer to be somehow different to Shape ... does Integer also have Instance and Constructor?)
    4. try to describe what is difference between unset Integer, and uninitialized Class
      (Tip: Error: "object not set to an instance" when you forget to call constructor of shape and you are trying to obtain value of some property. Just use this code for this research "Dim i As Integer : MsgBox i.ToString || Dim a As Square : MsgBox a.xlocation" -- this is related to pt 3)
    5. try to modify shape class and also square class for: square provides only Width to end user, or square provides both, but when setting Width Height is also set and reversely.
    6. try to modify circle class: so it provides only Diameter and/or Radius, while these both are only exposing Width. Don't expose Height, and try to find good compromise for 5 & 6 request, while both require some particular changes in base class (using Protected-Public method to expose or not base method/property in derived class)
    7. Ace of interest: do you think you would be able to provide two Square properties from Circle, which would, when used to SET, modify its Width (radius & diameter respectively) computing it from value set? In detail you would provided inside Square of Circle on GET, and you would accept such rectangle via SET as radius modification? Is there some way to reuse inside square computations for second, similar property outside square?
    8. Ace of interest: do you think you would be able to create 3D cylinder reusing (without its modification) current 2D Shape or Circle? You musn't inherit it - instead you can inherit base shape3D from shape and then inherit circle3D from it and cylinder3D from that. Can you somehow use instance of cylinder in cylinder3D?
    9. Ace of interest: after this all, check out your concept, are there some else conceptual mistakes as Michal pointed out? Do they have something common? Can you really take them as mistake, when you read my rest off link (while americans would just inherit person from address..)?
    10. Try to find some way how to distribute functions in hierarchy: can you also split some functions to functions as shown in Ball of Material? Can you move some of resulting functions to base so that MovingBall - Ball functional division appears?
    11. Try to decide if you just have closed this chapter, or if you need to practice and understand something more deeply (Class, Instance, Constructor, Providing / Exposing, Sense in dividing of bussiness, Sense in depicting a reality, MustInherit & MustOverride, Relation between Object and every class - reason of Overrides ToString, Private & Public, Protected & Public, Reasons of property & metaphores to it, Providing constructor, relation of Class and DATA, difference between Structure and Class ... probably I missed something? Classes WithEvents? Reflection?) ... or just find your own focus of interest :)
    12. If you will not run away lately, I would welcomed your code tuned up to perfection and showing all 1-10 points of knowledge about classes. I am pretty sure, that you are able to manifest such code, with no usage of internet, book except for 3 & 4. But also I recommend you to use it for any point if you are just not sure of some keyword, and for any case post your question here. This is not school paper ;) And I am pretty confusing teacher, at least! You have ten minutes. *
    13. Exit>_ Error: Object not set set to instance while trying (13).Exit

     

    ***learn to be the only one who govern coding priorities, don't let yourself confuse, try to preserve focus, do your own task list (or research mission plan :). Learn how to react if you are in some depth and you find some problem of its own depth, confusing you else with bulb-head problematic: is putting new problem to task list only solution? How to find out if new task can later, taken from task list, destroy your previous deep modifications? Etc... but mainly basic focus preserving and being "above" all problems outside focus is sufficient. Also even if you don't understand a thing, you should lead your helper to notice your focus or also interest...

    * four seconds to select your starting point from [1..10,13], and ten minutes to restart computer after microsoft update of ms office :) - ok I am really not prophet, but I am sure you can be much more proud of yourself after you get your book tuned.

    ///See you later, I am going to perform sleep cycle which takes usually 12 hours... uf, how would you implement "Fixation of iconic data using rotating windows"? Or what could it sign? I have bit deformed dreams probably :) But I would be really curious if you could propose e.g. some placement of such function? Does this ET use for reading .txt files, or it is only his scandisk? Peh. :P

    Regards, Matej

    • Edited by konikula Friday, November 14, 2008 7:21 AM context extension to pt3
    • Marked as answer by Xingwei Hu Wednesday, November 19, 2008 6:09 AM
    Friday, November 14, 2008 7:07 AM