I am making a simple C# console application to test inheritance but when I add 2 new classes and inherit one with another ( Mammal:Animal ) and make an object of mammal in the Program.cs class i-e
Program.cs
Mammal mam = new Mammal();
mam.see(only public function are showing of animal not the protected member of function)
Animal.cs
class Animal
{
protected void check()
{}
public void see()
{}
}
Mammal.cs
class Mammal:Animal
{
public void hair()
{}
}
Can't figure out why it is not allowing, as protected allows to inherit if they are in its hierarchy.
The code within Mammals has access to protected members of Animals, but only via an expression of type Mammals or a subtype.
From outside the class - which I assume this is - there's no access to protected members.
From section 3.5.3 of the C# 5 specification (emphasis mine):
When a protected instance member is accessed outside the program text of the class in which it is declared, and when a protected internal instance member is accessed outside the program text of the program in which it is declared, the access must take place within a class declaration that derives from the class in which it is declared. Furthermore, the access is required to take place through an instance of that derived class type or a class type constructed from it.
(As noted by Jonathan Reinhart, you almost certainly want these types to be called Mammal and Animal, by the way.)
Below is the way to access protected methods in derived class
class Animal
{
protected void check()
{}
public void see()
{}
}
class Mammal:Animal
{
public void CallSee()
{
Animal obja = new Animal();
obja.see();
}
}
Now you can create instance of class Mammal and call method callSee which will in turn call see method of Animal. As above answer suggestion proctected members are not accesible outside derived class. It can only be accessible in derived class
In Main Function write below code.
Static Main()
{
Mammal objm= new Mammal();
objm.CallSee();
}
The protected access modifier can be accessed only from within the declaring class or its sub classes...only public and internal makes a method accessible from outside
Related
Below code:
public class Program
{
static void Main(string[] args)
{
father f = new son(); Console.WriteLine(f.GetType());
f.show();
}
}
public class father
{
virtual public void show()
{
Console.WriteLine("father");
}
}
public class son : father
{
public override void show()
{
Console.WriteLine("son");
}
}
The result is 'son'.
If I modify the 'public override void show()' to 'public new void show()',the result is 'father'.
So I conclude below 'rules':
Use 'override', which function will be called is determined in run
time. The program will choose the right function according to the
real type of current object.(As above, the f's runtime type is son,
so it calls the son's show.)
Use 'new' modifier, which function will be called is determined when
it is compiled.The program will choose the object's declared type to
call its function.(As above, the f's declared type is father ,so
using 'new' modifier make the output to show 'father'.
All above are what I understand about polymorphism.Any misunderstanding and wrong?
Use 'new' modifier, which function will be called is determined when it is compiled.The program will choose the object's declared type to call its function.(As above, the f's declared type is father ,so using 'new' modifier make the output to show 'father'.
Not really. The decision is still made at execution time, but the new method does not override the virtual method in the base class. This is most easily shown by extending your example somewhat:
using System;
class Base
{
public virtual void Foo()
{
Console.WriteLine("Base.Foo");
}
}
class Derived : Base
{
public override void Foo()
{
Console.WriteLine("Derived.Foo");
}
}
class MoreDerived : Derived
{
public new void Foo()
{
Console.WriteLine("MoreDerived.Foo");
}
}
class Test
{
static void Main()
{
Base x = new MoreDerived();
x.Foo(); // Prints Derived.Foo
}
}
Here, at compile time the decision is made to call the most overridden implementation of Base.Foo - if there were multiple Foo signatures, the decision about which signature to use would be taken, for example. Which implementation will be "the most overridden" is unknown at this point, of course.
At execution time, the CLR will find that most overridden implementation based on the actual type of the target object - which is MoreDerived. But MoreDerived.Foo doesn't override Base.Foo... whereas Derived.Foo does, so the implementation in Derived is the one which is actually executed.
Use 'new' modifier, which function will be called is determined when it is compiled.The program will choose the object's declared type to call its function.(As above, the f's declared type is father ,so using 'new' modifier make the output to show 'father'.
This is slightly wrong. Using new means that this function does not override any functions of the base class. The function dispatch still happens at runtime, but this function is not considered. The difference would be clearer if you had Grandson or Daughter classes to test more.
yes it work like that only...your understanding is right..
But for second case when you use new intad of override it hide actual implementation i.e. parent class implementation
As the new keyword was used to define this method, the derived class method is not called—the base class method is called instead.
EXample from MSDN
// Define the base class
class Car
{
public virtual void DescribeCar()
{
System.Console.WriteLine("Four wheels and an engine.");
}
}
// Define the derived classes
class ConvertibleCar : Car
{
public new virtual void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("A roof that opens up.");
}
}
class Minivan : Car
{
public override void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("Carries seven people.");
}
}
call to the class
Car[] cars = new Car[3];
cars[0] = new Car();
cars[1] = new ConvertibleCar();
cars[2] = new Minivan();
output
Car object: YourApplication.Car
Four wheels and an engine.
----------
Car object: YourApplication.ConvertibleCar
Four wheels and an engine.
----------
Car object: YourApplication.Minivan
Four wheels and an engine.
Carries seven people.
----------
MSDN having good example of it : Knowing When to Use Override and New Keywords (C# Programming Guide)
A normal method is called by type of class and a virtual method is called by content of memory allocated to the object. Now keyword new hides the concept of polymorphic and just care for its type.
I was trying few things and would like to know why this is happening so.
Say, I have a class called A in namespace n and I was trying to create protected internal class B.
namespace n
{
public class A
{
public A()
{
}
}
protected internal class B //throwing error
{
}
}
But when i try like this (B as a sub class of A), its not throwing error and its built success. Could you explain me why it is so?
namespace n
{
public class A
{
public A()
{
}
protected internal class B // its not throwing error
{
}
}
}
Am i missing anything theoretically? Its quite a bit confusing.
A class can't be protected except when it is inside another class.
The protected keyword is only valid for members of a class. In your second example, class B happens to be that member.
Think about it:
protected means: Derived classes can access this member.
As there is no such concept as derived namespaces, the protected keyword doesn't make sense for members of a namespace.
Look at the error.
Elements defined in a namespace cannot be explicitly declared as
private, protected, or protected internal
Only internal or public members are allowed outside the class.
Your second case is defining the class B as member of class A that is why you are not getting the error.
You may see Access Modifiers C#
Classes and structs that are declared directly within a namespace (in
other words, that are not nested within other classes or structs) can
be either public or internal. Internal is the default if no access
modifier is specified.
protected declares visiblity level for derived types.
In your first case you declare class inside namespace. There is no any polymophic support for namespaces, so there is no any sence of using protected classes in namespace
In second case, instead, you use it inside other classe (class A), which make it visible for all children of A class.
Is it possible to override a base class method in C++, like we can do in C# using the override keyword ?
Please Help
Thank You
Yes.
Just make the base method virtual.
C++ doesn't have an override keyword; any method with the same signature (including parameter types and const-ness) as a virtual base method will override it.
Only in C++0x, the next upcoming standard of the C++ language. In C++03, that is the current C++ you override implicitly, that is you don't mark the overriding method explicitly as an overriding one. But be careful, if you accidentally write another signature but the same name, the base class function will be hidden and not overriden!
struct X
{
virtual void f() {...};
};
struct Y:X
{
void f() {...} //overrides X::f
};
struct Z:X
{
void f() const {... } //hides X::f!!!
};
The only thing that can differ in the functions' declarations is that if in base class the function returns T1* ( or T1&) and in derived class T2* (or T2&) and T2 is derived from T1 then it's OK, it's still overrifing, not hiding. HTH
Yes, you can override base class methods; if you use the keyword virtual in your base class, the binding of the method will be dynamic (i.e. fully polymorphic); if you don't use the keyword virtual in your base class, the binding of the method will be static.
A lot of answers have said you make a base class function virtual, this is often done but not needed. you could just do the following...
class A{
public:
void foo();
}
class B: public A{
public:
void foo();
}
class C: public A{
public:
void foo();
}
If you had an array of A pointers such as A* basePTR[2] you can instance basePTR[0] as an instance of B then basePTR[1] as an instance of C. but if you tried to call basePTR[0]->foo() you will call A::foo()
if you defined A as
class A{
public:
virtual void foo();
}
then calling basePTR[0]->foo() will call B::foo()
Their is overhead for using this functionality as at run time a look up has to be done to see if you are calling the base functions foo() or a derived class's foo() but normally, this feature is worth the relatively minor performance hit.
You could define A as
class A{
public:
virtual void foo() =0;
}
the =0 at the end of foo() means that this function is a pure virtual function, this means that it HAS to be defined by a derived class and you can't make an instance of A. A good example of where you would use this would be in a game, you might have a base class GameToken that has an XYZ position and a pure virtual function draw and update. from this you could derive player AI dynamicObject etc... your engine could then just store one array of type GameToken* and iterate through this array calling draw() and update() for all the different types in the array
I have created a class say A which has some functions defined as protected.
Now Class B inherits A and class C inherits B. Class A has private default constructor and protected parameterized constructor.
I want Class B to be able to access all the protected functions defined in Class A but class C can have access on some of the functions only not all the functions and class C is inheriting class B.
How can I restrict access to some of the functions of Class A from Class C ?
EDIT:
namespace Db
{
public class A
{
private A(){}
protected A(string con){assign this value}
protected DataTable getTable(){return Table;}
protected Sqlparameters setParameters(){return parameter;}
}
}
namespace Data
{
public class B:A
{
protected B():base("constring"){}
protected DataTable output(){return getTable();}
protected sqlparameter values(param IDataParameter[] parameter){}
}
}
namespace Bsns
{
public class C:B
{
protected C():base(){}
protected DataTable show()
{return values(setparameter());}
}
}
EDIT
I think what I am trying to do here is Multiple inheritance.
Please check.
class A
{
//suppose 10 functions are declared
}
class B:A
{
//5 functions declared which are using A's function in internal body
}
class C:B
{
//using all functions of B but require only 4 functions of A to be accessible by C.
}
You need to have classes A and B in the same assembly and class C in another assembly. You can mark the member you want to restrict access to by derived classes as protected internal. This makes the member, well, protected and internal. As far as limiting class C's access to the member it will suffice to mark it internal. Since this will make it it public within the first assembly, you might want to add protected to enforce encapsulation.
Turns out marking a member protected internal doesn't make it private to classes outside of the assembly. Seems that for all intents and purposes protected internal is the same as protected. Unfortunately the only way I can see achieving this would be to mark it internal and put up with the member being public to the defining assembly.
Even C# programming guide on MSDN gets it wrong:
By combining the protected and
internal keywords, a class member can
be marked protected internal — only
derived types or types within the same
assembly can access that member.
Phil Haack explains:
protected internal means protected OR
internal
It’s very clear when you think of the
keywords as the union of accessibility
rather than the intersection. Thus
protected interna means the method is
accessible by anything that can access
the protected method UNION with
anything that can access the internal
method.
Here is the updated code:
class A {
protected void Test3(){} //available to subclasses of A in any assembly
protected internal void Test() { } //Same as protected :(
public void Test2(){}//available to everyone
internal void Test4(){} //available to any class in A's assembly
}
class B : A {
void TestA() {
Test(); //OK
}
}
//Different assembly
class C : B {
void TestA() {
Test4(); //error CS0103: The name 'Test4' does not exist in the current context
}
}
It looks like you should probably using Composition not Inheritance.
Class A implements calc() and allow().
Class B has a private A but isn't derived from A
Class C derives from B and has no access to the private A object in class B.
I'd suggest that you rethink your design. Maybe there is a simpler way. What if C uses an instance of B instead of deriving from it (composition) ? That way C can use B's public methods but not get access to the protected ones.
Class A should not care about the level/depth of a descendant. If something is marked protected, it should be protected for both B and C (regardless of the depth of the inheritance chain).
B may choose to delimit its descendants by tightening the constraints (but this is rare).
If you can tell me more about your context - the problem you are trying to solve.. I can give you a more detailed/useful answer.
As others have said, you probably want to use composition instead of inheritance.
class A {
protected void Foo() { … }
protected int Bar() { … }
}
class B {
private A a;
public B() {
this.a = new A();
}
protected int Bar() {
return a.Bar();
}
}
class C : B { … }
Looking at your example, though, I would question whether C should inherit from B, or whether it should really just hold a reference to an object of type B.
Personally, I wouldn't go putting classes in different assemblies just for the purpose of restricting access if the class doesn't otherwise logically belong in a different assembly. There are other ways to handle it.
What are all the difference between an abstract class, and a class with only protected constructor(s)? They seem to be pretty similar to me, in that you can't instantiate either one.
EDIT:
How would you create an instance in a derived class, with a base class with a protected constructor? For instance:
public class ProtectedConstructor
{
protected ProtectedConstructor()
{
}
public static ProtectedConstructor GetInstance()
{
return new ProtectedConstructor(); // this is fine
}
}
public class DerivedClass : ProtectedConstructor
{
public void createInstance()
{
ProtectedConstructor p = new ProtectedConstructor(); // doesn't compile
}
public static ProtectedConstructor getInstance()
{
return new ProtectedConstructor(); // doesn't compile
}
}
You can instantiate a class with protected constructors from within the class itself - in a static constructor or static method. This can be used to implement a singleton, or a factory-type thing.
An abstract class cannot be instantiated at all - the intent is that one or more child classes will complete the implementation, and those classes will get instantiated
Edit:
if you call ProtectedConstructor.GetInstance(); instead of new ProtectedConstructor();, it works. Maybe protected constructors can't be called this way? But protected methods certainly can.
Here is an interesting article on the topic.
Most of the time, there is little practical difference, as both are only able to be generated via a subclass.
However, marking a class abstract has two benefits:
With protected constructors, it's still possible to create an instance of the class in two ways. You can use Activator.CreateInstance with BindingFlags.NonPublic, or you can use a factory method defined in the class (or a subclass) to create an instance of the class. A class marked abstract, however, cannot be created.
You are making your intention more clear by marking the class abstract. Personally, I find this the most compelling reason to do so.
From an outside , black-box perspective, yes they are similar in that you cannot instantiate either one. However, you can never instantiate an abstract class, where you can construct a class with only protected constructors from within the class itself, or from an inheritor.
An abstract class can have abstract methods; methods that consist only of the method signature, but no body, that child classes must implement.
Seriously, not one person mentioned that yet?
Your example is flawed because in the getInstance case because you construct a ProtectedConstructor class and expect to down cast it as a DerivedClass. Instead you need a slightly more complete implementation where the derived class has a constrcutor:
public class ProtectedConstructor
{
protected ProtectedConstructor(string arg)
{
// do something with arg
}
public static ProtectedConstructor GetInstance()
{
return new ProtectedConstructor("test");
}
}
public class DerivedClass : ProtectedConstructor
{
protected DerivedClass(string arg) : base(arg)
{
}
public void createInstance()
{
DerivedClass p = new DerivedClass("test");
}
public static DerivedClass getInstance()
{
return new DerivedClass("test");
}
}
Regardless the major difference usage of abstract classes is to define abstract methods that subclasses must implement but you don't want to provide a default implementation for. For example suppose you have some kind of Thread class that has a Run method. You want to ensure that every call to Run first setups up some logging then does the real work of the thread and then stops logging. You could write an abstract Thread class like this:
public abstract Thread
{
protected Thread()
{
}
public void Run()
{
LogStart();
DoRun();
LogEnd();
}
protected abstract DoRun();
private void LogStart()
{
Console.Write("Starting Thread Run");
}
private void LogEnd()
{
Console.Write("Ending Thread Run");
}
}
public class HelloWorldThread : Thread
{
public HelloWorldThread()
{
}
protected override DoRun()
{
Console.Write("Hello World");
}
}
Another thing to consider, that I didn't see other people mention, is that your code may be maintained in the future. If the maintainer adds a public constructor to a class, then it can be instantiated. This might break your design, so you should prevent it (or design to accommodate it).
To prevent other people from making these kinds of changes, you can comment your code. Or, as other people said, use "abstract" to explicitly document your intent.
Well, the first difference that comes to mind is that an abstract class can not be instantiated, but a class with protected constructors could be instantiated throw another public method.
A common example of this might be something like the Singleton pattern: http://en.wikipedia.org/wiki/Singleton_pattern
if you inherit an abstract class from another abstract class, you do not have to satisfy abstract methods, but you do with a normal class with protected ctors. Examples
public abstract class Parent
{
protected abstract void AMethod();
}
public abstract class Child: Parent
{
// does not implement AMethod, and that's ok
}
public class Child2: Parent
{
// does not implement AMethod, and that will cause a compile error
}
If your intent is to only allow static uses of the class (i.e. not to use it as a pure base class) then you should use the static keyword instead; the CLR will prevent instances of the class being created via any method including Reflection (AFAIK).