Let's have three classes;
Line
PoliLine
SuperPoliLine
for all that three classes a Distance
is defined.
But only for the Line
a Distance
can be Set.
Is there a possibility to build a common abstract (MustInherit) class Segment
, having a Distance
as (abstract +? ReadOnly) member?
Question for VB.NET, but C# answers welcomed too.
Business Background
Imagine a Bus. It has a lot of Station
s, MainStation
s, and 2 TerminalStation
s. So Line is between 2 Stations, PoliLine is between 2 MainStation
s, and SuperPoliLine
is between 2 TerminalStations. All "lines" are "Segments", but only the distance A->B between 2 stations - Line can be defined.
An abstract class not only contains abstract methods and assessors but also contains non-abstract methods, properties, and indexers.
Yes, you can have a private field within an abstract class. This field will only be accessible to functions within that abstract class though. Any classes which inherit from your abstract class will not be able to access the field.
A class property declared read-only is only allowed to be initialized once, and further changes to the property is not allowed. Read-only class properties are declared with the readonly keyword* in a typed property.
You can't override and re-declare (to add the set) at the same time - but you can do:
Base class:
protected virtual int FooImpl { get; set; } // or abstract
public int Foo { get { return FooImpl; } }
Derived class:
new public int Foo {
get { return FooImpl; }
set { FooImpl = value; }
}
// your implementation here...
protected override FooImpl { get { ... } set { ... } }
Now you can also override FooImpl as needed.
Since you want it settable in one class but unsettable in the others, I would customarily not use a property for the one that is “special” (the setter in this case).
public class Segment
{
protected int _distance;
public int Distance { get { return _distance; } }
}
public class Line : Segment
{
public int SetDistance(int distance) { _distance = distance; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With