Problems with the contructor/new() method in the subclass

  • Thread starter Thread starter Antuane
  • Start date Start date
A

Antuane

I've got a class as follows,

PUBLIC CLASS BaseClass

Sub New()
End Sub

Sub New(byval cName as String)
End Sub

Sub New(byval cName as String, nAge as Int16)
End Sub

END CLASS

PUBLIC CLASS Person
Inherits BaseClass
END CLASS


** Coding
If suppose i try the following piece of coding,
Dim oPerson as New Person("Jack", "Daniels")

"Then i get an error saying that the NEW method cannot accecpt so may
parameters

1. What have i done wrong?
2. I want to define such base NEW() - constructors, & do'nt want to write
these coding out in the subclasses.
But it seems taht i have to do so.

2. Is is possible for me to restrict the Sub NEW() contructor - the one
wihout parameters.
i.e. what i want to do is, when initializing the Person class, i want to
make it impossible to initialize this class by using the New() constructor
without any paramters.
Right now, what i do is,

PUBLIC CLass Person
Sub New()
THROW New Exception("Try using the Other Constructors which
accept parameters")
End Sub
.....

Is there another way of achieving the above?????
 
Antuane said:
I've got a class as follows,

PUBLIC CLASS BaseClass

Sub New()
End Sub

Sub New(byval cName as String)
End Sub

Sub New(byval cName as String, nAge as Int16)
End Sub

END CLASS

PUBLIC CLASS Person
Inherits BaseClass
END CLASS


** Coding
If suppose i try the following piece of coding,
Dim oPerson as New Person("Jack", "Daniels")

"Then i get an error saying that the NEW method cannot accecpt so may
parameters

1. What have i done wrong?

You've tried to call a constructor which doesn't exist. Constructors
aren't inherited. See the bottom of
http://www.pobox.com/~skeet/csharp/constructors.html for reasons why
this is a good thing.
2. I want to define such base NEW() - constructors, & do'nt want to write
these coding out in the subclasses.
But it seems taht i have to do so.
Yes.

2. Is is possible for me to restrict the Sub NEW() contructor - the one
wihout parameters.
i.e. what i want to do is, when initializing the Person class, i want to
make it impossible to initialize this class by using the New() constructor
without any paramters.

Just don't declare it then. A parameterless constructor is only
provided for you if you don't specify any other ones (I believe, anyway
- that's certainly true in C#, and from experimentation it appears to
be true in VB.NET too.)
 
Back
Top