When you derive from a class and instance the subclass, the runtime also instances the super class, right?
Since abstract classes can't be instanced, are they not created by the runtime when a subclass is instanced?
If so, then abstract class inheritance would be faster than normal class instance?
The runtime never creates separate instances of the base class and the derived class - it's just that the derived class instance also has all the variables etc of the base class, and runs the base class constructor as part of initialization. There's no difference here between "normal" base classes and abstract base classes.
I think you have some details confused.
When you construct an object, where the class of that object inherits from another class, it's not like you get two objects in memory.
You only get one, but it has space set aside for fields that comes from both.
Put another way, if the original class needs 10 bytes to hold its fields, and your inherited class needs 5 bytes to hold its specific fields, when you construct an object from your inherited class, it would occupy 15 bytes, where the first 10 corresponds to the fields from the base class. (note, this is a very simplified explanation, there's a lot more going on that dictates the actual size of objects).
Related
Nearly in all of the "Abstraction" principle definitions, it says sth. like "Hiding the irrelevant (or extra, not needed to know) codes from the user". And I could not get how this is about "abstraction".
Let's say "This is because we can define the methods in the base abstract classes, and we can use these methods after we created the objects in child classes without knowing the internal functionality" But we could already have base non-abstract classes for this purpose. We could have already created objects and used the functionality of the base class without knowing the internal structure of those methods. How is this feature belongs to "abstraction" ????
The main advantage of creating an abstract base class over a non-abstract base class is, that it can not be instantiated; so it is just be there for creating a "common concept", right? But other than that, i don't see a difference between them in the sense of hiding the internal structure.
Let's say I have 2 types of coffee-machine; CheapMachine and ExpensiveMachine. I created a non-abstract base class and added several methods with definitions like StartMachine(), GetOptimumHeat(), etc. And then I created a CheapMachine instance CP, and called these methods easily, without knowing the internal functionality of these methods.
So, did I use abstraction principle by just creating a base class then?
I am confused like I feel I got the main idea but what would be the best description of this principle? For ex., How would you describe this principle in an interview?
The title explains it all I believe.
In C#, I am now aware that regardless, constructors in derived classes will call a base class constructor whether it is an explicit call or an implicit default constructor. My question is why? I think it's because the derived class needs to create an object of the base class but why?
I think it's because the derived class needs to create an object of the base class but why?
An instance of a derived class is an instance of the base class. If you have a rule for what must happen when you construct an Animal, and you're constructing a Giraffe, then somehow you have to execute the rule for constructing an Animal. In C# that mechanism is "call a base class constructor".
A derived class is the base class plus extra things the derived class adds.
You still need some code that initializes the base class portion so you can add your extra parts on top. The call to the base constructor is where that initialization happens.
let's say the car is your abstract class and bmw,mazda,jeep are your driven classes.
you have fields: Name , Model,..
you have constroctor: car(),car(string model)
in car class, then when compiler doing memory allocation for object need to read abstract constructor to be aware of Name, Model.
this will call the default constructor. but you can use base("z4") to force calling overridden constructor in the abstract class.
As Scott Chamberlain said the derived class is something (plus some more features).
Of course an object can have behaviors in the constructor.
Anyway if you don't need to inherit them, you should structure your code in the right way,
you should leave base constructor empty, depends on your specific needs
I know and read about abstract class and interface but one point I never understood is that, what is the use of class which cannot be instantiated.
I can use normal class and virtual method instead of abstract class?
what will happen when I instantiate base class?
You typically use an abstract class when you have some set of common functionality to be shared between derived classes. That is, you cannot use an interface because you want to provide some default functionality.
Take a look at the System.IO.Stream class. This class provides some common base functionality, but requires that specific types of streams implement some members in order for it to function. These members are also tagged abstract, which indicates to the compiler and runtime that there is no suitable base-class implementation. A non-abstract class that derives an abstract class must override all inherited abstract members, just like a class that implements an interface must implement all members defined on the interface.
In the stream example, the Read() method is abstract, but the ReadByte() method is not -- because ReadByte() can be implemented in terms of a call to Read(). (Although not optimally, which is why ReadByte() is virtual, so that a more efficient implementation can optionally be provided.) Virtual members are different, because they do have an implementation, but can optionally be overridden. Abstract members have no implementation by default, and must be overridden.
In other words, methods on an abstract class can use other abstract members on the class, even though they have no implementation! This is because a derived non-abstract class is required to provide an implementation -- an implementation is guaranteed to exist at the point that the method is invoked. This is analogous to how you can use members of an interface even though the members have no implementation on the interface, because it's guaranteed that an object implementing the interface must implement all of its members.
Subclasses like MemoryStream and FileStream override all of the abstract methods to form a concrete class, and they can be instantiated. However, you are able to store them in a Stream reference variable and treat them like a generic "black box" stream. This allows you to declare a method that accepts a Stream object, and you don't have to care what kind of stream it actually is.
Stream foo = new Stream(); // Invalid, Stream is abstract.
Stream foo = new MemoryStream(); // Valid.
So, now to summarize the answers to the questions you posed in your title. An abstract class cannot be instantiated because it may contain members that are abstract and have no implementation. The use of an abstract class is twofold: first, to be subclassed and allow the subclasses to share a common implementation of some members, and second, to allow instances of any objects of subclasses to be used through references to the abstract class.
Abstract classes are very useful and it's all about design. If, for example, you have an abstract base class called Shape, which has functions such as 'Draw' and 'Move'. You then inherit the Shape class to create a 'Circle' class and 'Square' class.
The inherited classes both have the functions Draw and Move. Move may have functionality in the base class which the child classes use, but draw functionality is handled by each child.
While you then instantiate a Circle and Square, it is meaningless to have just a 'Shape' object.
Hope that helps.
Abstract and interfaces enable you to share some common logic but you can't instantiate, directlym any of them
To add to cdhowie answer the most relevant differences between interfaces and abstract classes are:
Inheriting from an abstract class forces child classes to be compromised with a chain of hierarchy. With interface different classes implementing it are completely loose from each other.
With abstract classes you can have methods or properties with logic, that is, some code is implemented itself in the abstract class. In interface there is no code or logic thus forcing implementors to write all the logic
Abstract class and interface class are language features both offering some compile time rules and some run time rules aiding design. So far instantiating abstract class or interface class goes, its not possible using the compiler for sure, if one were to program using assembly language for C++ or say intermediate language code/byte code for C# or Java it might be possible to instantiate them as well, I am not sure on this point though. Since at run time there is a type object for both abstract class and interface class.
I have a three classes A, B, and C shown below
public class A
{
public void add(int i, int k)
{
}
}
public class B:A
{
public void AddInt()
{
add(1, 2);
}
}
public class C
{
public void AddInt()
{
A objA = new A();
objA.add(1, 2);
}
}
We want access the "A" class method Add, there are two ways
1) Initiate the "A" class, then access the Add method
2) Inherit the "A" class, then access the Add method
If both those ways provide the same functionality, then why does C# provide two ways to achieve the same functionality.
What is the difference between initiating a class and inheriting a class?
First off, the word you're looking for is instantiate, not initiate.
What is the difference between instantiating a class and inheriting a class?
Inheritance expresses the "is a kind of" relationship between two classes:
The New York Times is a kind of newspaper.
A giraffe is a kind of animal.
An apple is a kind of fruit.
In each of these cases the first kind of thing is the "more derived" type -- it is more specific -- and the second thing is the "less derived" type, or "base" type. It is more general. More things are fruits than are apples.
In C# when you establish an inheritance relationship between two classes, you get two things:
Assignment compatibility: you can use an expression of the more derived type where an expression of the base type is needed.
Member inheritance: all methods, events, indexers, operators, fields, properties and nested types of the base class are automatically members of the derived class. (Constructors and destructors are not inheritable).
Instantiation is the process of making a new instance of a type.
Here, let me give you a copy of today's New York Times.
Here, let me give you a giraffe.
Here, let me give you an apple.
So in C#:
class Fruit {}
class Apple : Fruit { } // Apple inherits from Fruit
class Program {
static void Main() {
Apple apple = new Apple(); // Instantiating a new Apple
}
}
Make sense?
It's not about C# at all, it's about basic OOP concepts, that C#, in this case, simply manifests, being object oriented and strong typed language.
"Initialization" is a creation of an instance of a given type: A in your case.
Second example is a Polymorphism , where you derive from a given type A, and creating derived type B, is able to access public/protected members of the A class.
The access behaviour is the same in this case, but origin of that is completely different.
you are comparing Humans with food ... right no comparison
Initiating cost you some RAM of your system.
Inheriting lets you enable reuseability of common code
These two ways are available because your add method is public in class A. Change it to protected if you want to use it only in inherited classes. Simply saying inheritance makes all properties and methods except of private ones available in inherited classes. In your case class B is inherited from class A and instance of class B itself would be your instance to call method add on. In class C you simply created an instance of class A and called method add on it. All of this concepts would be much cleaner to you if you'll read about Access Modifiers and Inheritance.
Think of a class as a template, or plan, for how to build something. When you then use the template or plan to build one (think of architect plans for a house, and one of the many houses built from those plans), the words we use to describe this process are "Instantiation" and "Initialization".
You instantiate an instance of the object (build the house) using the class template (architects plan), and then initialize it (paint and decorate the house).
Inheritance, on the other hand, refers to something completely unrelated, in how classes are defined, using another existing class as a foundation or *base*line from which to start the definition of a new class that will extend the foundation or base class. When one class inherits from another, it means that "instances" of the derived class automatically get all the stuff that was defined in the parent base class without having to redefine it in the child.
A class is a type and acts as a template that allows you to create objects of this type. The creation of such objects is also called instantiation. This instantiation process involves allocating memory for this object (allocation) and then initializing this object, i.e. give its fields initial values. The latter is called initialization.
Inheritance is something completely different. Inheritance is about creating a new class (template) by inheriting existing code from a base class (also called superclass, or parent class).
This new derived class (also called subclass or child class) serves as template for the creation of a new type of objects.
The derived class can modify the behavior inherited from its base class and extend its possibilities. Inheritance creates a relation between the classes. Subclasses are assignment compatible with the superclasses above them in the inheritance hierarchy.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What's the difference between an abstract class and a static one?
Hello
I Would like to know what are all the differences between abstract classes and static classes in C#
When do I use what and why?
Is it true the abstract class is a class which we cannot create instances of it?
Thanks
I would like to know what are all the differences between abstract classes and static classes in C#.
Don't ask questions like that. I could spend hours listing hundreds of differences, none of which would be relevant to you.
What is the most important difference between abstract classes and static classes in C#?
That's more like it.
An abstract class is usually intended to model something in a type hierarchy. For example, a truck is a kind of vehicle, and an airplane is a kind of vehicle, so you might have a base class Vehicle and derived classes Truck and Airplane. But "Vehicle" is abstract; there are no vehicles which are just vehicles without being some more specific kind of thing. You represent that concept with an abstract class.
A static class by contrast is not intended to model anything at all. It's just a convenient way of storing a bunch of code. Really it shouldn't be a class at all; VB made a better choice by calling such things "modules" rather than "classes". Though technically they inherit from object, static classes are logically not really in a type hierarchy at all. They're just a bucket for holding static members.
Static classes are often used as containers of extension methods.
When do I use what and why?
Use an abstract class when you want to build a model of the form "an X is a kind of Y". Like "a Car is a kind of Vehicle" or "a Square is a kind of Shape" or "a Magazine is a kind of Publication", where the "Y" is an abstract concept. Don't use it for things like "an Employee is a kind of Person" -- Person should be concrete. Person is not an abstract concept; there are people who are just people, but there are no vehicles that are not something else.
Use a static class when you want to make extension methods, or when you have a bunch of code that fits logically together but does not associate with any object. For example, if you have a bunch of related math routines, that's a good candidate for a static class.
Is it true the abstract class is a class which we cannot create instances of it?
No. That is not true. You can create instances of an abstract class. You do so by creating an instance of a more derived class.
Vehicle v = new Car();
Clearly v refers to an instance of Vehicle, and therefore you can create an instance of an abstract class. What you cannot do is create an instance of an abstract class that is not also an instance of a more derived concrete class.
By contrast, you cannot create an instance of a static class at all.
Here's a question you didn't ask:
What is the implementation relationship between static classes and abstract classes?
Static classes actually do not really exist as a concept in the CLR. When you say "static" on a class, what we actually do is generate an abstract sealed class with no public constructors. Since it is abstract, you cannot create one directly. Since it is sealed, you cannot create a more derived class and instantiate that.
It's true that it's not possible to create an instance of an abstract or static class but that's about where the similarities end.
Can inherit from abstract cannot inherit from static
Can have instance methods on abstract cannot have instance on static
An abstract class can implement an interface a static class cannot
Fundamentally they are trying to serve two different purposes
An abstract class forms a blue print / pattern which is then implemented in derived classes in different and (hopefully) transparent ways
A static class is simply a container for a collection of possibly related static methods
An abstract class is a class that must be inherited to be used — it can only be inherited.
You can create instances of classes that inherit it.
A static class is a class that cannot have instances at all; such a class only has static members.
static classes cannot be inherited, nor can they inherit other classes.
True, an abstract class cannot be instantiated, but instead forms the base of other classes. The benefit is that you can put functionality into the abstract class to aid reuse.
A static class is one that is instantiated by the CLR when required. There can only be one instance of it any time. Using static classes is very useful, but care must be taken around threading and simultaneous access.