Class to inherit the constructor of its base class - c#-4.0

I would like to know if I can access the constructor of the base class in its derived classes in C#. If yes please let me know how could we make it. Thanks in advance.

You can call the base class constructor as part of the execution of the derived class constructor
public MyBase
{
public MyBase() { }
}
public Derived
{
public Derived() : base() { }
}
When using this pattern, you are said to be using the base class initializer.
For more background, see the base keyword and instance constructors on MSDN.

Related

UML class diagram for static variable from other class

As I know, if the static method from other class, we may interpret their relationship with dependency, just like the answer from How to show usage of static methods UML Class Diagram
However, how about for the static variable from other class? Is it the similar case; using dependancy?
For example,
class A{
public static String CHAR="Charecter";
public static String INT="Integer";
public static String STR="String";
}
class B{
public String Type;
public B(){
Type=STR;
}
public void B(String t){
Type=t;
}
}
would it result in the uml class diagram as below?
Note that although I would rather use enumeration in real life for this case, I just would like to know how it works.
Yes, this is similar.
Dependency shows that one class is "aware" of some other class and uses it in some way (or more generally depends on it). It can for instance refer to (public) static attributes, static operations and so on.

Differences between Abstract Factory Pattern and Factory Method,confused by one case

The main difference between a "factory method" and an "abstract factory" is that the factory method is a single method, and an abstract factory is an object. But, sometimes I can't say what it is,for example
class Product{
}
interface Facotory{
public Product create();
}
class FactoryA implements Facotory{
public Product create() {
return null;
}
}
class FactoryB implements Facotory{
public Product create() {
return null;
}
}
Can you tell me it is factory method or abstract factory?Thank you!
IMO, Your current example above is Factory Method.
As you have defined an interface (Factory) with a factory method (create) that allows sub classes (FactoryA and FactoryB) to decide which class to instantiate (Product derived classes).

Calling one specific overriden method in all derived classes

Consider the following code:
// ======== Abstract class ========
public abstract class Creatures {
public abstract void loseEnergy();
public void execute()
{
loseEnergy();
}
}
// ======== Animals ========
public class Animals : Creatures
{
public override void loseEnergy(){}
}
public class Birds : Animals
{
public override void loseEnergy(){}
}
// ======== Human ========
public class Human : Creatures
{
public override void loseEnergy(){}
}
public class Male : Human
{
public override void loseEnergy(){}
}
public class Female : Human
{
public override void loseEnergy(){}
}
[ This code was based on the code by Jayson suggested here: "Base class methods calling derived class methods ?" ]
In the given code example, I would like to have the runtime executing EACH derived class object's certain method, in this case, which is 'loseEnergy()', however, I could not find the solution.
How do I approach this problem?
What can be useful to know or to try.. in order to solve this issue?
Your help is very much appreciated!
Thank you!
Kind regards,
Segara
P.S. Some search I have done so far:
"How to call overriden methods in all derived classes"
"Collection of derived classes that have generic base class"
"How to call derived function using base class object"
"Call method of the derived class through reflection possible or no"
EDIT:
I decided to stick to the idea I had before which is to have some list that would contain the objects of the classes that have 'loseEnergy()' method. Having such list I will be able to call every object's method 'loseEnergy()', which is what I wanted.
Question can be closed.
Thank you.
I didn't really understand your problem but anyway i can try to give you some means to use abstract classes :
If you use a abstract method, you SHOULD override it in a subclasses (like a method declared in an interface)
If you want that all inherited class use a same method, you can implement it in the abstract class ; all subclasses will use the method you implements if you don't override it, you've have to not declare it in the subclasses (extends < ABS_CLASS > is good enough)
If you want use a method of the abstract class which is override in the sub class you can use the keyword super .
I hope it will help you.
if you mean that you want the calls: female.loseEnergy() -> human.loseEnergy() -> creature.loseEnergy(), call the base method in the first line of the overriden one
public class Female : Human
{
public override void loseEnergy()
{
base.loseEnergy();
// do stuff
}
}
In the Greenfoot environment that you mention in the post above, the act() method is called only on actors which have been added into the "world". Internally, this adds them into a list. The simulation process iterates through the list and calls act() on each object in turn. Objects that are not "in the world" are not known to the system and so do not have their act method called. There is no magic here going on here.
If you wanted similar behaviour but without manually adding objects into a list, you could possibly have the base class constructor add new objects into a global list. I don't know C# so I don't know precisely how to do this, but I cannot imagine it would be difficult.

Does not contain a constructor that takes 0 arguments

I get an error stating "Products does not contain a constructor that takes 0 arguments" from the following code:
public class Products
{
string id;
string name;
double price;
int soldCount;
int stockCount;
public Products(string id, string name, double price,
int soldCount, int stockCount, double tax)
{
this.id = id;
this.name = name;
this.price = price;
this.soldCount = soldCount;
this.stockCount = stockCount;
}
}
//I have got some get and set values for the code above
//but it would have been too long to put in here
public class FoodProducts : Products
{
public FoodProduct()
{
Console.WriteLine("This is food product");
}
public void Limit()
{
Console.WriteLine("This is an Attribute of a Product");
}
}
Several rules about C# come into play here:
Each class must have a constructor (In order to be, well constructed)
If you do not provide a constructor, a constructor will be provided for you, free of change, automatically by the compiler.
This means that the class
class Demo{}
upon compilation is provided with an empty constructor, becoming
class Demo{
public Demo(){}
}
and I can do
Demo instance = new Demo();
If you do provide a constructor (any constructor with any signature), the empty constructor will not be generated
class Demo{
public Demo(int parameter){}
}
Demo instance = new Demo(); //this code now fails
Demo instance = new Demo(3); //this code now succeeds
This can seem a bit counter-intuitive, because adding code seems to break existing unrelated code, but it's a design decision of the C# team, and we have to live with it.
When you call a constructor of a derived class, if you do not specify a base class constructor to be called, the compiler calls the empty base class constructor, so
class Derived:Base {
public Derived(){}
}
becomes
class Derived:Base {
public Derived() : base() {}
}
So, in order to construct your derived class, you must have a parameterless constructor on the base class. Seeing how you added a constructor to the Products, and the compiler did not generate the default constructor, you need to explicitly add it in your code, like:
public Products()
{
}
or explicitly call it from the derived constructor
public FoodProduct()
: base(string.Empty, string.Empty, 0, 0, 0, 0)
{
}
Since Products has no constructor that takes 0 arguments, you must create a constructor for FoodProducts that calls the constructor of Products will all the required arguments.
In C#, this is done like the following:
public class FoodProducts : Products
{
public FoodProducts(string id, string name, double price, int soldCount, int stockCount, double tax)
: base(id, name, price, soldCount, stockCount, tax)
{
}
public void Limit()
{
Console.WriteLine("This is an Attribute of a Product");
}
}
If you don't want to add this constructor to FoodProducts, you can also create a constructor with no parameter to Products.
the constructor of the inherited class needs to construct the base class first. since the base class does not have a default constructor (taking 0 arguments) and you are not using the non-default constructor you have now, this won't work. so either A) add a default constructor to your base class, in which case the code of the descending class needs no change; or B) call the non-default constructor of the base class from the constructor of the descending class, in which case the base class needs no change.
A
public class Products
{
public Products() { }
}
public class FoodProducts : Products
{
public FoodProducts() { }
}
B
public class Products
{
public class Products(args) { }
}
public class FoodProducts : Products
{
public FoodProducts(args) : base(args) { }
}
some of this is explained rather OK on msdn here.
As you inherit from Products, you must call a base construct of Products in your own class.
You didn't write:base(id, name, ....) so C# assumes you call the default parameterless constructor, but it doesn't exist.
Create a default parameterless constructor for Products.
Just add
public Products()
{
}
in your products class And you will not get error
Reason:
There exists a default constructor with 0 parameter for every class. So no need to define/write it explicitly (by programmer) BUT when you overload a default constructor with your desired number and type of parameters then it becomes a compulsion to define the default constructor yourself (explicitly) along with your overloaded constructor

Calling protected method in base class via pointer to base class in derived class

I would like to understand why when I call protected method, declared and implemented in base class, from derived class via pointer to base class I get compilation error (C2248) and when I call it from derived class via pointer to derived class instance, compilation pass.
I understand it is part of the language but I want to understand why
My explanation is that when I call a protected member of base class via pointer to base class in derived class, compilation fails because the inheritance of base class can be protected or private but when I call it via pointer to derived class in a derived class it o.k because it is part of the class.
Is that right?
e.g.
class Base
{
protected:
virtual void func() {}
}
class Derived : public Base
{
public:
virtual void myMethod()
{
Base* pBase = new Base;
pBase->func(); -> compilation error (C2248)
Derived* pDerived = new Derived;
pDerived->func(); -> O.K
}
}
The failing line is not compilable because you are accessing an instance of Base - only public methods can be accessed this way. If you do this in myMethod():
Base::func();
it should compile because now we are accessing the inherited method for this. Kind of weird to have pDerived::myMethod() call the Derived constructor?

Resources