I have a base class and several subclasses derived from that base class. I also have a static function in the base class that takes some parameters, and instantiates and returns an appropriate subclass based on input parameters ( my factory method.)
Now here's my problem: I want to ONLY allow instantiation of the subclasses FROM the factory method. But if I set the constructors of the subclasses to be protected, the base class can't see them. Is there an access modifier I'm missing that would allow the base class to call the subclasses constructors, but not not allow any other classes to call them?
Internal doesn't look like it will work either...I want to limit access to the subclass constructors to just the base class, there are other classes in the same assembly that should be able to access the base factory method and but not directly instantiate any of the subclasses.
Hopefully there's something really simple I'm missing...
Example:
public class Base
{
public Base CreateChild(string childType)
{
if(childType == "A")
return new ChildA();
if(childType == "B")
return new ChildB();
return null;
}
}
public class ChildA
{
protected ChildA() // This doesn't work, since now base class can't call this!
{
}
}
public class ChildB
{
protected ChildB()
{
}
}
You can declare the child classes as private nested classes inside Base
Have you tried declaring the child classes within the base class?
public class Base {
protected class ChildA {}
protected class ChildB {}
}
If accessing any derived object through the base type is a valid scenario (let's say derived types only override base implementations and do not add new functionality) then the proposed solution of making the derived types nested private classes (as previous answers propose) is the best solution.
If that's not the case then I think you are falling into a case of unjustified complexity. What is the reason why code from your same assembly can not access ChildA and ChildB constructors? It is after all code you can control, so you can always choose to make / enforce via code review that he initalization is through the factory method.
I understand there is valid reasons to not let external assemblies freely instantiate objects except through a tightly controlled mechanism. In this case just marking the constructors as internal would do.
Otherwise, I'm not sure you can achieve what you are pretending without creating a specific assembly just for this base class and its derived classes. There is definitely no access modifier that would make a static method in a derived class only visible from it's base class.
Related
I have following easy class design, where myObject is importing for BaseClass.
public abstract class BaseClass
{
public BaseClass(myObject parameter)
{
// ...
}
}
public class ChildClass : BaseClass
{
}
My problem is now, that I want to make my program extensible by inheriting from public BaseClass. So you could create a constructor
public ChildClass() :base(new myObject()){...}
which will lead to failures. Is there a possibilty to prevent inherited classes with own constructors? I actually would like to avoid constructors for ChildClass at all. Is this possible? Then I could use a factory and provide an Initialize method. Or is this something impossible, where I simply must be aware of and check in my code=
Classes are completely responsible for their own constructors. They aren't inherited, and every class must have a constructor. So no, there's nothing you can do to "control" what constructors a base class can or can't have.
I know we cannot create an abstract class instance, but I cannot understand why could use base invoke the constructor of the abstract class.
abstract class Fruit
{
public string Name { get; private set; }
public Fruit(string name)
{
Name = name;
}
}
class Apple : Fruit
{
public Apple(string name) : base(name) { }
}
Fruit f = new Fruit("Fruit"); // Coimple Error
Apple a = new Apple("Apple"); // Success
Dose that base keyword just invoke constructors, methods, etc?
What's the differences between create an instance and invoke a constructor?
Thanks in advance.
Only derived class (e.g. Apple) can call the constructor of its parent (abstract class) with special base word. Constructor cannot be invoked (called) directly.
I would add that the fact that an abstract class may provide a constructor doesn't mean that it's not yet abstract.
By definition, an abstract class is a class where some or none of its members don't provide a default implementation, and derived classes must provide an implementation to these members. In the other hand, since an abstract class has some of its members as just signatures - the whole abstract members -, code mustn't be able to instantiate that class.
But if a derived class - either abstract or concrete - couldn't be able to call a base abstract class constructor, abstract classes would lack polymorphic constructors and there may be no way to initialize class properties or define a default class initialization code, even if that code calls an abstract method or property.
This is why a derived class can call a parent class constructor, even if the class is abstract!
What's the differences between create an instance and invoke a
constructor?
We might try to address this question with a deep explanation with low-level details, but
I feel that it's more a conceptual issue rather than a low-level thing.
If you want a summary, calling the constructor is a part of class instantiation process. It's a method which is called once the instance has been created and initializes the instances with custom code before any other code might use that instance.
When you use base keyword in a constructor to call parent's class one, you're just chaining constructor calls from the most derived class to the base class.
Does that base keyword just invoke constructors, methods, etc?
No, use it anytime you want to explicitly invoke the parent class' methods and avoid invoking a override in the derived class. Though : base(...) syntax is exclusive to constructors, usually you would call base.method();
What are the differences between create an instance and invoke a constructor?
Creating an instance with the new operator does a number of things:
Allocates memory for the object
Initialises fields
Then finally the constructor is invoked, which will invoke base constructor first if specified.
A more in-depth explanation of the order is in this answer: https://stackoverflow.com/a/1882778/360211 but that should be enough to explain the difference.
Creating an instance with the new keyword creates a new object and returns a reference to the object.Invoking the constructor with the base keyword won't create a reference to the object(neither it will create an actual object), it will simply execute the code in the constructor.
Take a deep look onto this answer to for more information https://stackoverflow.com/a/14453366/3789232
I read an article from some site and in that article i read this :
Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.
I don't understand what it means. Can anyone explain this more specifically , with a Good Example ?
this is the article which i read Link
Because interfaces only define members that types must implement, adding any new member to an interface will break any class that implements the old version because it inherently doesn't implement the new member. Any time you change the definition of an interface you must change every single class that implements that interface. Adding an abstract member to an abstract class does the same for derived classes but if you add a virtual member to the abstract class then it will have no impact on derived classes. They can be changed to override that member but they don't have to.
What it means is that if you consider a Abstract Class called Phone
and it has 3 virtual functions i.e.
AddPhonePrice , AddAccessoryPrice, AddAuxillaryPrice
and if there are two child classes
1) SamsungPhone 2) Iphone
now SamsungPhone will have implementation for all 3 functions.
while Iphone will have implementation for only AddPhonePrice, since they dont provide anything else with the phone
if we make interface called IMainPhone with
AddPhonePrice , AddAccessoryPrice, AddAuxillaryPrice functions
then both SamsungPhone and Iphone will need to implement all 3 functions
irrespective of whether they need them or not.
This means that you are able to add new members (methods, properties, fields, ...) to abstract classes that do not lead to changes in the derived classes - as long as the members are not abstract this is correct. For instance, consider this example:
internal abstract class MyBaseClass
{
public abstract void DoSomething();
// This method can also be added later without having an effect on the derived classes
public virtual void DoSomethingElse()
{
// Do something else...
}
}
internal class MyDerivedClass : MyBaseClass
{
public override void DoSomething()
{
// Do something...
}
}
In this case, the derived class has to implement the method DoSomething. But you can add non-abstract functions to the abstract base class later on. However, as soon as you add another abstract member to the base class, this also affects all non-abstract derived classes because the must implement the new members.
An interface on the other hand does not define concrete implementations at all but does only contain the abstract signature that all implementors must provide. Therefore, if you add a new member (method, property) to an interface it forces all implementors of the interface to also provide an implementation of the new members.
Interface: When you add a method to the base interface class, then you have to (manually) make sure all of the derived classes implement that method.
Abstract Base: When you add a method to an abstract base class, you aren't required by the compiler to implement that method in the derived classes.
How can I prevent inheritance of some methods or properties in derived classes?!
public class BaseClass : Collection
{
//Some operations...
//Should not let derived classes inherit 'Add' method.
}
public class DerivedClass : BaseClass
{
public void DoSomething(int Item)
{
this.Add(Item); // Error: No such method should exist...
}
}
The pattern you want is composition ("Has-a"), not inheritance ("Is-a"). BaseClass should contain a collection, not inherit from collection. BaseClass can then selectively choose what methods or properties to expose on its interface. Most of those may just be passthroughs that call the equivalent methods on the internal collection.
Marking things private in the child classes won't work, because anyone with a base type variable (Collection x = new DerivedClass()) will still be able to access the "hidden" members through the base type.
If "Is-a" vs "Has-a" doesn't click for you, think of it in terms of parents vs friends. You can't choose your parents and can't remove them from your DNA, but you can choose who you associate with.
You can't, in this instance inheritance is the wrong tool for the job. Your class needs to have the collection as a private member, then you can expose as much or as little of it as you wish.
Trying to hide a public member of a class in a derived class is generally a bad thing(*). Trying to hide it as a means of ensuring it won't be called is even worse, and generally won't work anyhow.
There isn't any standardized idiomatic means I know of to prevent a parent class' protected member from being accessed in a sub-derived type, but declaring a new public useless member of a clearly-useless kind would be one approach. The simplest such thing would be an empty class. For example, if class Foo declares an empty public class called MemberwiseClone, derivatives of Foo will be unable to call MemberwiseClone--probably a good thing if MemberwiseClone would break the invariants of class Foo.
(*) The only situation where it is appropriate is when a public method of a derived class returns a more specialized type than the corresponding method in the base class (e.g. a CarFactory.Produce() method may return a Car, while the FordExplorerFactory.Produce() method may return a FordExplorer (which derives from car). Someone who calls Produce() on what they think is a CarFactory (but happens to be a FordExplorerFactory) will get a Car (which happens to be a FordExplorer), but someone who calls Produce() on what is known at compile time to be a FordExplorerFactory will get a result that's known at compile time to be a FordExplorer.
The C# spec, section 10.1.1.1, states:
An abstract class is permitted (but
not required) to contain abstract
members.
This allows me to create classes like this:
public abstract class A
{
public void Main()
{
// it's full of logic!
}
}
Or even better:
public abstract class A
{
public virtual void Main() { }
}
public abstract class B : A
{
public override sealed void Main()
{
// it's full of logic!
}
}
This is really a concrete class; it's only abstract in so far as one can't instantiate it. For example, if I wanted to execute the logic in B.Main() I would have to first get an instance of B, which is impossible.
If inheritors don't actually have to provide implementation, then why call it abstract?
Put another way, why does C# allow an abstract class with only concrete members?
I should mention that I am already familiar with the intended functionality of abstract types and members.
Perhaps a good example is a common base class that provides shared properties and perhaps other members for derived classes, but does not represent a concrete object. For example:
public abstract class Pet
{
public string Name{get;set;}
}
public class Dog : Pet
{
public void Bark(){ ... }
}
All pets have names, but a pet itself is an abstract concept. An instance of a pet must be a dog or some other kind of animal.
The difference here is that instead of providing a method that should be overridden by implementors, the base class declares that all pets are composed of at least a Name property.
The idea is to force the implementor to derive from the class as it is intended to provide only a basis for a presumably more specialized implementation. So the base class, while not having any abstract members may only contain core methods an properties that can be used as a basis for extension.
For example:
public abstract class FourLeggedAnimal
{
public void Walk()
{
// most 4 legged animals walk the same (silly example, but it works)
}
public void Chew()
{
}
}
public class Dog : FourLeggedAnimal
{
public void Bark()
{
}
}
public class Cat : FourLeggedAnimal
{
public void Purr()
{
}
}
I think a slightly more accurate representation of your question would be: Why does C# allow an abstract class with only concrete members?
The answer: There's no good reason not to. Perhaps someone out there has some organizational structure where they like to have a noninstantiatable class at the top, even if a class below it just inherits and adds nothing. There's no good reason not to support that.
You said it -- because you can't instantiate it; it is meant to be a template only.
It is not "really a concrete class" if you declare it as abstract. That is available to you as a design choice.
That design choice may have to do with creating entities that are (at risk of mixing the terminology) abstractions of real-world objects, and with readability. You may want to declare parameters of type Car, but don't want objects to be declarable as Car -- you want every object of type Car to be instantiated as a Truck, Sedan, Coupe, or Roadster. The fact that Car doesn't require inheritors to add implementation does not detract from its value as an abstract version of its inheritors that cannot itself be instantiated.
Abstract means providing an abstraction of behaviour. For example Vehicle is an abstract form. It doesn't have any real world instance, but we can say that Vehicle has accelerating behaviour. More specifically Ford Ikon is a vehicle, and Yamaha FZ is a vehicle. Both these have accelerating behaviour.
If you now make this in the class form. Vehicle is abstract class with Acceleration method. While you may/ may not provide any abstract method. But the business need is that Vehicle should not be instantiated. Hence you make it abstract. The other two classes - Ikon and FZ are concrete classes deriving from Vehicle class. These two will have their own properties and behaviours.
With regards to usage, using abstract on a class declaration but having no abstract members is the same as having the class public but using protected on its constructors. Both force the class to be derived in order for it to be instantiated.
However, as far as self-documenting code goes, by marking the class abstract it informs others that this class is never meant to be instantiated on its own, even if it has no virtual or abstract members. Whereas protecting the constructors makes no such assertion.
The compiler does not prevent implementation-logic, but in your case I would simply omit abstract ?! BTW some methods could be implemented with { throw Exception("must inherit"); } and the compiler could not distinguish fully implemented classes and functions including only throw.
Here's a potential reason:
Layer Supertype
It's not uncommon for all the objects
in a layer to have methods you don't
want to have duplicated throughout the
system. You can move all of this
behavior into a common Layer
Supertype.
-- Martin Fowler
There's no reason to prevent having only concrete methods in an abstract class - it's just less common. The Layer Supertype is a case where this might make sense.
I see abstract classes serving two main purposes:
An incomplete class that must be specialized to provide some concrete service. Here, abstract members would be optional. The class would provide some services that the child classes can use and could define abstract members that it uses to provide its service, like in the Template Method Pattern. This type of abstract class is meant to create an inheritance hierarchy.
A class that only provides static utility methods. In this case, abstract members don't make sense at all. C# supports this notion with static classes, they are implicitly abstract and sealed. This can also be achieved with a sealed class with a private constructor.