How can I use setters in the concrete class? I have two abstract classes and the bottom concrete class should be able to set all the private variables I have the abstract classes, how can I do that?
I could just add getters and setters in my concrete class, but because I have 4 derived classes from my second abstract class, I don't want to have duplicate code and a long list of public properties, any way to resolve that?
I am working in C#
Using the protected keyword in c# you can access the variables in parent objects
Like this
public abstract class Parent {
protected int integer {get;set;}
}
public class Child : Parent {
public Child(int value) {
integer = value;
}
public int getValue() {
return integer;
}
}
see : https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected
From Microsoft documentation :
private
The type or member can be accessed only by code in the same class or struct.
protected
The type or member can be accessed only by code in the same class, or in a class that is derived from that class. internal The type or member can be accessed by any code in the same assembly, but not from another assembly.
private protected
The type or member can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class.
So doesn't matter if the class is abstract or not, private can only be accessed within the same class.
Related
I have a class
abstract class EmployeeBase
{
}
I want that this EmployeeBase should not be used as a property in any of my other classes. Only a class derived from EmployeeBase can be used to declare a property in any other class. Is it possible to achieve that? If so, how?
You can get close to this this by making EmployeeBase a protected subclass of the class you wish to derive from:
public class OuterClass
{
protected abstract class EmployeeBase { /*...*/ }
}
However, keep in mind this will prevent any properties of type EmployeeBase from being exposed as public or internal, since you can't expose an object with a less exposed type, since any consuming code wouldn't know the signature of the object. EDIT You could, however, expose them by interface or other base type.
While you can restrict inheritance from EmployeeBase by making all constructors internal, restricting use of a type is not well supported in C#, and raises many questions about what exactly you're trying to do.
You cannot create instance of abstract class so there will be no variable or property created as EmployeeBase
You have to inherit from EmployeeBase so I believe your problem is already solved ;)
public abstract class EmployeeBase{}
public class Employee: EmployeeBase{}
class SomeClass
{
public EmployeeBase Employee { get; set; }
SomeClass()
{
Employee = new Employee(); // OOP in play :)
Employee = new EmployeeBase(); // Error CS0144
// Cannot create an instance of the abstract class or interface 'EmployeeBase'
}
}
Are private members inherited when inheriting the class in c#?
I have read some topic related to this, somebody telling that private members are inherited but cannot access the private members, somebody telling that it is not inherited when inheriting the class. Please explain the concept. if it is inheriting can any body give an explanation?
thanks
If I understand your question correctly then you're not concerned about the accessibility you are only concerned about private members are inherited or not
Answer is yes, all private members are inherited but you cant access them without reflection.
public class Base
{
private int value = 5;
public int GetValue()
{
return value;
}
}
public class Inherited : Base
{
public void PrintValue()
{
Console.WriteLine(GetValue());
}
}
static void Main()
{
new Inherited().PrintValue();//prints 5
}
You can mark things as protected, in which case you can access them from derived types.
Edit: In terms of whether they inherit, then yes they do. The child class is still of the parent classes type, and thus inherits everything. The child just cannot access it directly, but if you call base class methods that use the private parent field, that would work fine.
Private members can't be inherited, only protected which are like extended private members.
Like Sriram says, yes, private members do get inherited, but they ar enot accessible.
If they would not get inherited, protected or public properties references private members would break in inherited classes.
class myBase
{
private string _myProp;
protected string MyProp
{
get
{
return _myProp;
}
set
{
_myProp = value;
}
}
}
class myChild : myBase
{
public myChild()
{
_myProp = "SomeString"; // This will fail!!!
this.Myprop = "SomeString"; // This works
}
}
Here in the child class, you cannot access _myProp directly as it is private in the base class. However, the memeber is inherited, so it is accessible through the protected property MyProp.
Members marked as private can be accessed only on the type where they are defined. You cannot access them from derived types.
Members marked as protected can be accessed on the type where they are defined and on derived types.
Members marked as internal can be accessed only from the assembly where the type is defined.
You may combine the protected and the internal access modifier.
When talking about values of private members: Of course they are inherited. A derived class always also is of the type of the base class. If the base class holds a private value to store some data, the derived class will do that, too - only that you can't access that value from the derived class.
Please also read the relevant article on Accessibility Levels in the MSDN.
What you said about private fields being inherited is totally right.
Here what happens: A subclass will inherit the behaviour of your base class. That behaviour might need some fields to work. So, your subclass will reserve some space for them, but you will not be able to manipulate those fields, only by using methods (public and protected ones)
In other words, your sub class inherits base class fields by holding them in memory, but it cannot access them.
On low level, it is your compiler that prevents you from accessing/changing those private fields, but even using reflection you can still do so.
If you need any clarification, let me know
From http://msdn.microsoft.com/en-us/library/ms173149.aspx
A derived class has access to the public, protected, internal,
and protected internal members of a base class. Even though a
derived class inherits the private members of a base class, it
cannot access those members. However, all those private members are
still present in the derived class and can do the same work they would
do in the base class itself. For example, suppose that a protected
base class method accesses a private field. That field has to be
present in the derived class in order for the inherited base class
method to work properly.
To expand on what's been said, privates can be accessed by a subclass when inner scope is in play. For example, the following will compile:
class A
{
private int _private;
class B : A
{
void Foo()
{
this._private = 2;
}
}
}
Short answer: yes, but you are unable to access them directly.
When class A is derived from class B, and B has a private property then that property will be there for an instance derived of class A. You are, however unable to access it. It must be there because the behavour specified in class B depends on it.
funfact:
It is actually possible to still access the private property with a thing called reflection. But don't worry about that and you should not use reflection for this purpose unless you really need to know what is going on and what you're doing.
The simplest answer you can not access the private variables of base class in derived class directly but yes this private objects and values are initialized in base class when overriding class object is initiated (thus base class variables are inherited) and you can access them using some property or function if base class exposes them.
To make explanation more clear,
class A
{
private int i;
private int j;
protected int k;
public A()
{
i = j = k = 5;
}
}
class B : A
{
private int i; //The same variable exist in base class but since it is private I can declare it
private int j;
private int k; //Here I get warning, B.k hides inherited member A.k'. Use the new keyword if hiding was intended. F:\Deepak\deepak\Learning\ClientUdpSocketCommunication\ClientUdpSocketCommunication\Program.cs 210 25 ClientUdpSocketCommunication
private int l;
private int m;
private int n;
public B()
{
i= j = this.k = l = m = n = 7; // Here I have used this.k to tell compiler that I want to initialize value of k variable of B.k class
base.k = 5; //I am assigning and accessing base class variable as it is protected
}
}
If an object of class B is initialized then, A.i, A.j, A.k variable will be initialized, with B.i, B.j, B.k, B.l variables and if base class exposes function or properties then I can access all the base class variables.
Some say here that if members are protected you can access them:
Are private members inherited in C#?
Did someone really tried ?
I have tried it doesn't even work with protected:
public partial class Base
{
protected IObject myObject;
}
If I derive (Base is in another namespace but it shouldn't matter I of course import that namespace)
public partial class Derive: Base
{
}
Intellisense doesn't show myObject in Derive Class.
So what I can do if I need a myObjhect member in all my derived classes to call some methods upon ? If I have to duplicate that member then what's the use of inheritance ?
Update: I forgot Derive:Base but that was just mystypo, of course I did that.
You aren't deriving. To derive, you have to do the following:
public class Base
{
protected IObject myObject;
}
public class Derive : Base
{
}
myObject is available in Derive now. Partial means you are splitting the class definition over multiple files.
You have to actually derive from the Base class:
public partial class Derive : Base
{
}
A derived class has access to the
public, protected, internal, and
protected internal members of a base
class. Even though a derived class
inherits the private members of a base
class, it cannot access those members.
However, all those private members are
still present in the derived class and
can do the same work they would do in
the base class itself. For example,
suppose that a protected base class
method accesses a private field. That
field has to be present in the derived
class in order for the inherited base
class method to work properly.
From: http://msdn.microsoft.com/en-us/library/ms173149.aspx
check this
Aren't you missing the base class when deriving? Should work with myObject declared as protected.
public partial class Derive : Base
{
}
In c# we can't create an obeject of a abstact class or interface it means abstract class do not have any constructor, is it true ?
or if it have then what is it's purpose there?
As others have said, abstract classes usually have constructors (either explicitly or the default one created by the compiler) - and any derived class constructor will have to chain through the abstract class's constructor in the normal way. That's the important bit... suppose you have an abstract class which stores the name associated with an instance - because you always want a name, and you don't want to write the Name property in each concrete derived class. You might provide a constructor which takes that name and assigns it to a field... and then every subclass constructor would have to go through that constructor, so that you still knew you'd always have a name. If you want to know more about constructor chaining, read my article on it.
Here's an example of that:
public abstract class DemoBase
{
private readonly string name;
public string Name { get { return name; } }
protected DemoBase(string name)
{
this.name = name;
}
// Abstract members here, probably
}
public class FixedNameDemo : DemoBase
{
public FixedNameDemo()
: base ("Always the same name")
{
}
// Other stuff here
}
public class VariableNameDemo : DemoBase
{
public VariableNameDemo(string name)
: base(name)
{
}
// Other stuff here
}
To further answer your comment on BoltClock's answer, asbtract classes can't have private abstract methods, but they can have private constructors. Indeed, it's sometimes useful to have only private constructors in an abstract class, because it means the class can only be derived from within the program text of the same class. This allows you to create pseudo-enums:
public abstract class ArithmeticOperator
{
public static readonly ArithmeticOperator Plus = new PlusOperator();
public static readonly ArithmeticOperator Minus = new MinusOperator();
public abstract int Apply(int x, int y);
private ArithmeticOperator() {}
private class PlusOperator : ArithmeticOperator
{
public override int Apply(int x, int y)
{
return x + y;
}
}
private class MinusOperator : ArithmeticOperator
{
public override int Apply(int x, int y)
{
return x - y;
}
}
}
In this respect, an abstract private method/property could make sense - it could be accessed by the base class but provided by the derived classes within the same class's program text. However, it's prohibited by the specification. Usually, protected abstract members would solve the same problem - but not quite always.
Good question. Here's why Abstract classes need constructors even though they cannot be instantited.
In any Object oriented language like C#, object construction is an hierarchical process. Look at the code below. When you instantiate any object of type DerivedClass, it must construct the base object first before creating the object of typeof DerivedClass. Here the base class may or may not be an Abstract class. But even when you instantiate an object of a concrete type derived from an abstract class it will still need to call the constructor of the Base class before the object of DerivedClass type is created, hence you always need a constructor for Abstract class. If you have not added any constructor, C# compiler will automatically add a public parameterless constructor to the class in the generated MSIL.
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("BaseClass constructor called..");
}
}
public class DerivedClass : BaseClass
{
public DerivedClass()
{
Console.WriteLine("DerivedClass constructor called..");
}
}
DerivedClass obj = new DerivedClass();
//Output
//BaseClass constructor called..
//DerivedClass constructor called..
PS: Assuming, If Abstract base classes
are not allowed to have constructors
because they need not be instantiated,
the whole fundamentals of the object
oriented programming will go on toss.
The idea behind Abstract types are to
represent objects that have some
features and behaviours but not
complete as whole to allow independant
existence.
No. it means that operator new is not allowed to create object from this type of class.
The purpose might be that are allocated/initialized some properties of class.
abstract usually leave some methods to implement.
Regarding the interface, this structure holds only the signatures of method, delegates or events. That may be implemented in class that use interface. You cant create a object.
Read about new
EDIT:
What is the purpose of constructor in abstract class ?
When one class inherit another class, the parent class of it had to be created first while object is crated. In class do not implement some special constructor always is used default one [className()]. When you override some method then the implementation of functionality is taken form class which override the method. This is why method used in constructor should never be virtual. Same logic for abstract class, such class can have a lot of functionality, and only one method that should be implemented by child class.
Abstract classes have constructors but you can't call them directly as you can't directly instantiate abstract classes.
To answer your comment, the concept of a private abstract method or property makes no sense, because private prevents anybody else from accessing it, and abstract prevents itself from accessing it. So there would essentially be no possible way to call it.
EDIT: see Jon Skeet's answer on private constructors. Private members of other kinds cannot exist in abstract classes, though.
Abstract classes do have constructors. When you create an instance of a derived class, its parent class' constructors are called. This applies to classes derived from abstract classes as well.
Just seen one tutorial saying that:
Class Dog
{
private string Name;
}
Class SuperDog:Dog
{
private string Mood;
}
Then there was an UML displaying that SuperDog will inherit Name as well. I have tried but to me it seems that only public members are inherited. At least I could not access Name unless it was declared as public.
A derived class has access to the
public, protected, internal, and
protected internal members of a base
class. Even though a derived class
inherits the private members of a base
class, it cannot access those members.
However, all those private members are
still present in the derived class and
can do the same work they would do in
the base class itself. For example,
suppose that a protected base class
method accesses a private field. That
field has to be present in the derived
class in order for the inherited base
class method to work properly.
From: http://msdn.microsoft.com/en-us/library/ms173149.aspx
So, technically, yes, but practically, no.
Everything from the base class is
inherited to derived class. members
marked private are not accessible to
derived classes for integrity purpose,
should you need to make them
accessible in derived class, mark the
members as protected.
There are various levels of members' accessibility in context of inheritance.
public: all public members of the base-class are accessible within the derived-class and to the instances of derived-class.
protected: all protected members of the base-class are accessible within the derived-class and not to the instances of derived-class.
protected internal: all protected internal members of the base-class are accessible within the derived-class and to the instances of derived-class created within the same assembly.
internal: all internal members of the base-class are accessible within the derived-class and to the instances of derived-class within the same assembly.
private: no private members of the base-class are accessible within the derived-class and to the instances of derived-class.
private protected: The type or member can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class.
SuperDog will inherit the Name field, yes.
SuperDog will NOT have access to the field though, so there is no practical use (as far as SuperDog is concerned).
Private members can be visible inside a derived class: (If the subclass is nested within the base class)
public class Person
{
private string message;
public override string ToString()
{
return message;
}
public static Person CreateEmployee()
{
return new Employee();
}
class Employee : Person
{
public Employee()
{
this.message = "I inherit private members!";
}
}
}
Credit for the example goes to KodefuGuru in this thread at MSDN.
Yes, although heirs cannot access that member.
If you with that they will be able to access it, declare it as protected.
No, they aren't.
The protected modifier can make fields available to derived classes, but this is generally considered a bad idea from a maintenance perspective. You'd want to use protected properties instead.
try the keyword protected, instead of public/private:
http://msdn.microsoft.com/en-us/library/bcd5672a(VS.71).aspx
Make Name protected or public instead, that will be accessible. Private members are not accessible from derived classes
Private members are not accessible to descendants of a class.
I'm not sure of all the access modifiers, but at the most basic only public and protected members are accessible.
Yes, The are inherited.
But you cannot access them as they are private :).
As others have said private members are inherited. Member access is a different subject but not totally disjoint from an inheritance perspective. It is important to understand that all members are inherited regardless of their access modifier because it effects the sizes of the subclasses. Consider the following code.
public class Foo
{
private int a;
public int b;
}
public class Bar : Foo
{
private int c;
public int d;
}
Foo will consume 16 bytes on the heap. 4 for the syncblock, 4 for the type information (method table), and 4 each for the int variables for a total of 12. Bar, on the other hand, will consume 24 bytes. 4 for the syncblock, 4 for the type information (method table), 4 each for the int fields inherited from Foo, and 4 each for the int fields in Bar for a total of 24.
People have said it, but here's an example of why you need the private fields in the derived class:
class Program
{
static void Main(string[] args)
{
var r = new Random();
foreach(var i in Enumerable.Range(0,100))
new Derived(r).Printer();
Console.Read();
}
}
public class Base
{
private Random r;
public Base(Random r) { this.r = r; }
protected void Print()
{
Console.WriteLine(r.Next(1, 10000));
}
}
public class Derived : Base
{
public Derived(Random r) : base(r) { }
public void Printer()
{
base.Print();
}
}
You are right, private members aren't accessible by the derived class.
You should either make the members protected or access them using the public methods of the base class.
class Player
{
protected string name;
protected string type;
public Player(string name,string type)
{
Console.WriteLine("Player"+ this);
this.name = name;
this.type = type;
}
public void introduce()
{
Console.WriteLine("I am " + this.name + " I'm a " + this.type);
}
}
class Wizard : Player
{
public Wizard(string name,string type):base(name,type)
{
Console.WriteLine("Wizard"+ this);
}
public void Play()
{
//protected modifier made the name field available;
Console.WriteLine("Yipeeee!!!!!"+ " "+ this.name);
//on the other hand
// we can make the name and type fields as private in the base class and access them using the public methods of the base class
introduce();
}
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But yes they really are