Inheritance: only fields and methods? - c#

Reading a book it says that the derived class inherits all fields and methods...but what about properties??

There seems to be a considerable amount of misinformation in the answers here. For the correct answer, see section 3.4 of the C# specification, which I reproduce for you here:
Members of a type are either declared in the type declaration or inherited from the base class of the type. When a type inherits from a base class, all members of the base class, except instance constructors, destructors and static constructors, become members of the derived type. The declared accessibility of a base class member does not control whether the member is inherited—inheritance extends to any member that isn’t an instance constructor, static constructor, or destructor. However, an inherited member may not be accessible in a derived type, either because of its declared accessibility or because it is hidden by a declaration in the type itself.
I have added some emphasis to the relevant part. The key is that all members are inherited except for constructors and destructors. Members are inherited regardless of whether they are methods, fields, properties, events or indexers. Members are inherited regardless of whether they are public, private or protected. Members are inherited regardless of whether they are static, instance, virtual or abstract. All members are inherited.

A derived class inherits all methods fields and, yes, properties too, although private methods, fields and properties are generally not directly accessible or visible from the derived class unless it is nested in it's superclass (the parent). Constructors and finalizers, however, are not inherited so when you derive a type you always need to code any constructors that are required for your object initialization, even if it just calls down to the base class's constructor.
However, it is generally considered good practice to make your fields private and allow access to them, if necessary, to derived classes via properties. That way it allows you, the author of the base class, to have confidence that you control the way in which the classes state (the value of it's fields) can change.
To illustrate you question about properties:
public class Person
{
public Name { get; set; }
public void Greet()
{
Console.WriteLine("Hello");
}
}
public class Child : Person
{
public Nickname { get; set;}
}
In the above example, the derived class, Child, has a nickname (a property) in addition to its derived property (Name) and its derived method (Greet).

A property is syntactic sugar for a Get_ and Set_ method.
In other words: the compiler translates a property to one or two methods. So, they're inherited as well. :)

In a word, yes, properties are inherited along with the fields and the methods. Both private and public methods, fields and properties are inherited, but private members are inaccessible by the child class (unless the child class is nested within the base class - scoping and inheritance are connected but different things).
Properties, as implemented in C# (and most other languages that support them) are just a code-level abstract for a pair of methods that get and set the property, so having a int property called Age, is syntactic sugar for a couple of methods that are called int GetAge() and SetAge(int value), so it's natural that any rules that apply to methods applies evently to properties too.

Related

Why cannot ceate an abstract class instance but can invoke its constructor?

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

What is the difference between a child of a parent class and the derived of a base class in VB.NET or C#?

After asking the question Call a method that requires a derived class instance typed as base class in VB.NET or C# on Stack Overflow, I was informed that I had used the wrong terms when asking the question. I had used "parent" and "child" where I should have used "base" and "derived" instead.
I have been unable to find a good description of the difference.
This is what I know (or think I know) so far:
A parent class contains the child class. Where as a derived class inherits from a base class.
They are similar because the child (or derived) can access the parents (or base) properties and methods (where allowed).
They are different because you can refer to a property of the child class in the form of Parent.Child.Property. Whereas you cannot do that with a derived class.
What is the difference and in what situation should one be used over the other?
parent and child are more abstract relations. They are used to describe hierarchy, and thus can be used in all kinds of trees (or sometimes DAGs).
The tree of class inheritance is one such tree, so calling them parent and child is not wrong.
This terminology is often used with other kinds of trees, such as nested GUI controls, directory structures,...
base and derived is used only for inheritance, and thus more precise. This terminology is preferred, since it's less ambiguous.
Parent/Child is used in both contexts. It can be used to describes a "contains" relationship as you mentioned (Parent.Child.Property) or it can mean a derived class (also called a subclass).
Bottom line is - to understand what is meant by Parent/Child you have to know the context.
In any case, the difference between the two concepts (inheritance vs. encapsulation) can be thought of as a "is-a" and "has-a" relationship.
A dog is an animal (inheritance)
A car has an engine (encapsulation)
When a class is derived from a base class it is called inheritance. You inherit when you want to add functionality to an existing component, or extend the component.
When a class is referenced by/contained in a parent class it is called encapsulation. You encapsulate when your (usually parent) object 'uses' components.
From Ext - Inheritance vs. Encapsulation:
When do you inherit and when do you encapsulate? You inherit when you
want to add functionality to an existing component. You encapsulate
when your object 'uses' components. You inherit if your new class "is
a" Ext Component. You encapsulate if your new class "has a" Ext
Component.
Here is a link that takes a look at inheritance and encapsulation in object oriented programming in detail and discusses which concept is better in which situation.
Derived in OOP esplicitly defines polymorphic relationship between types:
public class A{
}
public class AB : A{
}
class AB is derived class from A.
Parent and Child is a definiton of abstract relationship, that in programming can get different shapes like:
public class A{
}
public class ParentA{
List<A> children = ...
}
usually used in Graph like relationships
Parent and child have to do with the OO principle of encapsulation, whereas base and derived have to do with the principle of inheritance.
A child class in encapsulated by the parent class, exposing only public methods of the child and having no direct access to the parent.
A derived class has access to all the properties, methods and members of the base class that are exposed as protected or higher access modifiers.
"Parent" is a synonym for "base" and "child" is a synonym for "derived", but "parent" and "child" are uncommon and not very technical (and don't sound very good IMO). Two other terms are "superclass" and "subclass".
Based on the way you are using Parent / Child, I think you mean nested classes.
class Container
{
class Nested
{
}
}
A nested class is private by default. The purpose here is typically that Nested will be a helper class used by Container. For example, Nested could be used by a method in Container that needs to return multiple values. An instance of Nested or Container would require a reference to the other to access any of its non-static members.
Where as a derived class inherits from a base class
class Base
{
}
class Derived : Base
{
}
A derived class has all of the functionality of its base class and can be used anywhere the base class can be used. An instance of Derived has access to all of the public and protected non-static members. Base does not have access to any members of Derived. Additionally, Derived can override the behavior of virtual members of Base.
Avoiding the terminology parent/child I just want to mention that it is possible for a nested class to have its own containing ("outer") class as its base class. I don't think it's a pattern people use very much, but it's allowed in the language (C#).
An example:
class MyClass
{
// we choose to make the instance constructor private
MyClass()
{
}
// nested type, private to MyClass, deriving from MyClass
class InnerMyClass : MyClass
{
// ...
}
public static MyClass GetMyClassInstance()
{
return new InnerMyClass();
}
// ...
}

c# abstract methods: internally public and virtual?

Are abstract methods internally public and virtual in c#?
All methods are, by default, private and if an abstract method is private, it will not be available to derived class, yielding the error "virtual or abstract members cannot be private"
I think you are asking a different question than most people think (in other words it seems like you understand what abstract means).
You cannot declare a private abstract method - the compiler issues an error. Both of these classes will not compile:
class Foo
{
private abstract void Bar();
}
class Baz
{
// This one is implicitly private - just like any other
// method declared without an access modifier
abstract void Bah();
}
The compiler is preventing you from declaring a useless method since a private abstract member cannot be used in a derived class and has no implementation (and therefore no use) to the declaring class.
It is important to note that the default access modifier applied to an abstract member by the compiler (if you do not specify one yourself) is still private just like it would be if the method was not abstract.
Abstract is just a way to say: "I am here, but no one has told me what I'm going to do yet." And since no one has implemented that member yet someone must do that. To do that you have to inherit that class, and override that member.
To be able to override something it has to be declared either abstract or virtual, and must at least be accessible to the inheritor, i.e. must be marked protected, internal or public.
Abstract methods cannot be private and are virtual. They must be at least protected.
By virtue of Jon Skeet's argument here (What are the Default Access Modifiers in C#?)
The default access for everything in C# is "the most restricted access you could declare for that member"
It must be "protected"
As pointed out by Pieter default is always private, so:
abstract class Foo
{
abstract void Bar();
}
Gives compiler error
virtual or abstract members cannot be private

How to prevent inheritance for some methods?

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.

Why should constructors on abstract classes be protected, not public?

ReSharper suggests changing the accessibility of a public constructor in an abstract class to protected, but it does not state the rationale behind this.
Can you shed some light?
Simply because being public makes no sense in an abstract class. An abstract class by definition cannot be instantiated directly. It can only be instantiated by an instance of a derived type. Therefore the only types that should have access to a constructor are its derived types and hence protected makes much more sense than public. It more accurately describes the accessibility.
It technically makes no difference whatsoever if you make the constructor public instead of protected on an abstract class. The accessibility/visibility of the constructor is still exactly the same: the same class or derived classes. The two keywords have indistinguishable effects for all intents and purposes.
So, this choice is only a matter of style: type protected to satisfy the Object Oriented savvy people.
Reflection will by default only include the constructor when it is public, but you cannot call that constructor anyway.
IntelliSense will show the public constructor when typing new, but you cannot call that constructor anyway.
The assembly's metadata will reflect the fact that the constructor is public or protected.
It is good OO practice.
public abstract class ExampleAbstractClass
{
protected ExampleAbstractClass()
{
// :::
}
}
You only want the inheriting child classes to have access to the constructor. The only way to do that is by making the constructor protected.
Keep in mind, when you add parameters to these constructors, it is an entirely different discussion.

Categories

Resources