Where virtual constructors are used? - oop

I read about virtual constructors are used for implementing some design patterns, but didn't understood any need of virtual constructors. So what are virtual constructors and why we really need them?

In most programming languages, afaik, you cannot find virtual constructors. Which override of a virtual members are evaluated at runtime after an object is constructed, but in most languages you need to know the actual class when constructing the instance. Therefore virtual constructors make no sense in these languages.
In .NET, you can get a similar solution through reflection, i.e. you can construct an object through an instance of the Type class that represents the object you want to construct. And with generic support, you can also achieve something similar, but it's not virtual constructors.
The only programming language that I have worked with that have true virtual constructors is Delphi. In Delphi, there is a specific "Metaclass type", i.e. a specific programming construct that represents a metaclass (whereas in .NET, the meta class, the Type class, is just an instance of a normal class). So if you have a class called TMyClass - Deplhi naming conventions ;)
TMyClass : Class ...
You can declare the metaclass like this
TMyMetaClass : class of TMyClass
Now, you can declare a variable that is of TMyMetaClass type,
MyMetaClassVariable : TMyMetaClass
...
// Assign the meta class to refer to our concrete class
MyMetaClassVariable := TMyClass;
And you can construct a new instance through this variable
MyClassInstance := MyMetaClassVariable.Create();
Now, the MyMetaClassVariable can refer to any class that is either TMyClass or a specialization thereof. If the constructor is declared virtual, then the variable will be constructed with an instance of that specific class.
In the same way, you can declare virtual static methods in Delphi, and call them through an instance of the metaclass.
So the other question? Why do we need them? Well, in Delphi, they solve some of the same problems as the Type class in .NET, allowing you to construct objects where you don't know the class name at design time.
For example, when you design a form and you put in a bunch of controls, this data has to be serialized by the designer, and deserialized. When the form is deserialized, then it is actually the metatypes that are read, and the correct instances (be it TextBox, ComboBox, etc) are constructed by calling the virtual constructor on the metatype.

Related

Can we replace abstract class with Interface with Default Methods in C#

In C# 8.0 we have a new feature where we can provide a default method implementation in Interfaces which can also be overridden by its implementing classes as well.
We used to have Abstract classes with instance methods to provide a common functionality for all of its implementing classes.
Now can I replace those Abstract classes who are having Instance methods with Interfaces who are having Default method implementations from C# 8.0 on wards?
No, abstract classes still have their place. In particular, abstract classes can declare fields (often via automatically implemented properties these days), which interfaces still can't. They can also define constructors, and perform validation in them.
Here's an example of something you couldn't do with an interface:
public abstract class NamedObject
{
public string Name { get; }
protected NamedObject(string name) =>
Name = name ?? throw new ArgumentNullException(nameof(name));
// Abstract methods here
}
Obviously it wouldn't really be called NamedObject - there'd be a business-specific reason for it to be abstract, which would determine the name. But the behaviour here is behaviour that can't be put in an interface.
You can in most cases but probably you shouldn't. The default functionality in the interfaces is there to solve another problem.
It's there for when you can't change an existing class, if for example is in some other project/ibrary and you want to extend the functionality without changing all the code with an abstract class..
Maybe it does make sense to have as an Abstract class? An object that has behavior but does not make sense on its own and must be extended should be better modeled by a class. If you have the Car class with behavior, then you can have the length private member which applied to all cars. Private members are not part of the interfaces.

Is class an object in object oriented language

Is class an object in object oriented language? How are Class methods accessed by just name of the class.method name? (internal working). Is this same as a object.method?
And If the Class is same as object (belong to object class which is super class of every thing in OO) and we instantiate it (make object of it), can we make instance of an instance of an class other than Object class.
(Mainly interested in the theoretical perspective even if practically not required ever)
Well, it depends on the language that you are using; in pure OO languages where everything is an object (e.g. Smalltalk) classes are no exception and are objects too. In other languages where classes are not considered as first class citizens they are just special language constructs or primitive types. From now on I'll use Smalltalk as a target language, due to its reflection support and homogeneous style.
How Class methods are accessed by just name of the class.method name?
(internal working). Is this same as as object.method?
Since classes are objects, they are in turn instances of a class (a metaclass). Thus, sending a message to the class is just sending a message to an object whose role is to represent how classes behave. There is a lot of literature out there, you can take a look for example here and here for some introduction.
And If the Class is same as object (belong to object class which is
super class of every thing in OO) and we instantiate it (make object
of it), can we make instance of an instance of an class other than
Object class.
I'm not sure I follow you here, but just for clarification it is not always the case that Object is the superclass of all the classes. The thing is that If you start following the relationships between classes and metaclasses, you may reach a sort of infinite loop. Different languages work this out in different ways and for example, in VisualWorks Smalltalk, Object is a subclass of nil. The thing is that nil is also an object (remember, everything is an object) and it actually represents "nothing". As you may expect, nil is an instance of a class (UndefinedObject) and it also implements some of the class protocol. As a result it can be used to represent a class form where nothing is inherited :).
Finally, I don't know if this answers your question, but yes, you can do many cool things with full reflective capabilities, like creating new classes on the fly or reshaping existing ones. I'll leave you here some documents that you may find interesting regarding this topic:
Metaclasses
Understanding Metaclasses
Debugging Objects
A class isn't an object, you can think of it as a 'blueprint' for an object. It describes the shape and behaviour of that object. Objects are instances of a class.
See here for more information.
Is class a object in object oriented language?
The notion of class is first and foremost theoretical. You can define a thing with "class" semantics even if your language does not support the formal notion of "class" (e.g. Javascript). A class is a template for an object, from which you create instances.
How Class methods are accessed by just name of the class.method name?
I'm not quite sure what you mean. Some languages support "static" or "class" methods, which are methods that are not invoked within the context of an instance of the class. So its not the same as "object.method" which is a normal method on the class where the 'this' (or equivalent) will be the instance on which the method is invoked.
Java (from comments)
For Java, there is a class called Object, and a class called Class. See this. These Java constructs are separate from the notion of Class and Object. The former are implementation details -- they are how the designers constructed the language, the latter are general concepts. So in Java, you can have an instance of an Object, where the instance is an object(the concept) of type Object(the Java construct).
A Basic notion of object means that has been allocated some memory. As devdigital said class is just a blueprint for an object which holds the bare-bone structure and determines how the object will behave when it's it will be instantiated.
Classes are just bodies(without soul) and objects are living bodies(having a soul) that interact with environment or in biological terms respond to external stimuli(public methods and properties) in an analogy to philosophy of life :)
Technically classes are just machine interpretable code residing in memory(not necessary main memory or registers). Objects are code loaded into executable memory(registers/main memory)

Inheritance Fundamentals

class Base
{
}
class Derive:Base
{
}
Base b=new Derive();
The above code works,but why we are able to create a Object of Derive Class and assigning it to Base Class reference.
Also,the object variable 'b' will be able to access all non private variable and methods of Class Base,even though it is referencing Derive Class.
What makes this possible,why the object variable 'b' which is referencing Derive Object is able to access the Base Class and not the Derive Class.
The theory allowing the above code to work is called the substitution principle: When Derived is a subtype of Base, this forms a "is-a" relationship. The substitution principle postulates that wherever an instance of Base is expected, it can be substituted by an instance of Derived.
The reason you cannot access the properties and methods of the Derive class later on is that (at least to a computer) there is no indication whatsoever that a variable of type Base contains an instance of type Derive which would allow access to these properties/methods. If you take another class DerivedToo : Base which has other methods than Derive you quickly see how the program could break if you assumed the Base variable to hold a Derive instance.
I think this is polymorhism question rather than inheritance.
One of the key features of derived classes is that a pointer to a derived class is type-compatible with a pointer to its base class. Using polymorphism you can take advantage of this feature.
Polymorhism allows you to invoke derived class methods through a base class reference during run-time. This is handy when you need to assign a group of objects to an array and then invoke each of their methods. They won't necessarily have to be the same object type. However, if they're related by inheritance, you can add them to the array as the inherited type.

Is there any static language in which a class is an object?

There are quite a few dynamically typed object oriented languages in which a class itself is an object. Smalltalk, and Python for example. Is there any statically typed language in which a class is an object?
EDIT:
By the term "object", I mean a first class entity. For example, classes in Python can be passed to other methods, can be returned from methods etc.
In a lot of statically typed languages, like JAVA, a class is an object with its own methods.
For example, in Java, the object that represents the "String" class is accessible as "String.class" and then you can invoke methods on this class as "String.class.getFields()", "getMethods()", getConstructor()", "cast(obj)", etc. You can see in the API documentation all the methods of the "Class" class.
Nevertheless, given that the language is statically typed, you cannot dynamically modify a class.
In other words, you are not going to find a method called "class.addField()" in the Class class. The more you can do is "extend" the class (if it is not final) by inheritance.
In yet other words, the a "Class" object is read-only.
By the term "object", I mean a first class entity. For example, classes in Python can be passed to other methods, can be returned from methods etc.
As any other object, you can pass them to methods and return them from methods (they are just regular objects, but that expose only "read" methods). Example (I omit generics for clearness):
public Class myMethod(Class someClassObject) {
System.out.println(someClassObject.getCanonicalName());
Class anotherClass = String.class;
return anotherClass ;
}
I don't fully agree with #edutesoy answer.
First-class means that an implicit constructs is reified as an explicit construct that can be passed around like any object. Classes in Java are not "first-class", they are mirrors where you can inspect some properties but are not the the object itself.
That you can not change the structure of the class at run-time is fine, e.g. add fields, change method body or signature, and that under this perspective it's partly "read-only" is ok.
But let's consider static fields. I guess everybody agrees that unless final static fields are mutable, just like instance fields. In Smalltalk, these are just fields defined on the class itself, rather than on instances of the class. Also, in Smalltalk, class-side methods are polymorphic just like any other method, and :
aClass field: aValue.
might resolve differently depending on the class that is passed. This is not possible in Java ; a static field or method must be referenced via its type. This also means that it does not allow overriding static methods (read the link for more details) as would be the case if they were truely first class.
The fact that reflection is possible in Java doesn't make classes "first-class"--you can only pass a representation of the class around. And to come back to the original question: I don't know of any statically typed language with first-class classes (but my knowledge is limited, maybe one exists).
EDIT
Actually, now I remember it exists StrongTalk (http://www.strongtalk.org/) which is Smalltalk with static typing. The typing issues are discussed in this paper: Strongtalk: Typechecking Smalltalk in a Production Environment
From Oleg Kiselyov and Ralph Lammel's "Haskell's overlooked object system" (emphasis mine),
Not only OOHaskell provides the conventional OO idioms; we have also
language-engineered several features that are either bleeding-edge or unattainable
in mainstream OO languages: for example, first-class classes and class closures; statically type-checked collection classes with bounded polymorphism of implicit collection arguments; multiple inheritance with user-controlled sharing; safe co-variant
argument subtyping.
Well, the benefits of that are reduced in an early-bound language. However, Java reflection objects for classes would basically be what you are asking for.
Why, incidentally, do you want this? Is it more than idle curiousity?
Take a look at the concept of homoiconicity which refers to the extant that a language can refer to its own structures. Also take a look at this post by Eric Lippert.

MustInherit and Shared Functions

I'm looking at a VB.NET class (that I didn't write) that is declared MustInherit (abstract in C#, I believe) that has three methods, all of which are defined as Shared (static in C#). There are no properties or fields in the class - only the three methods. From an OO perspective, does this make any sense?
My thinking is no, because by making it MustInherit, you're essentially saying you can't create an instance of this class - you must inherit from it and create an instance of the derived class. But since all the methods are shared, you'll never actually create an instance of the parent class anyway, so the MustInherit does no good. You might as well not mark it MustInherit and just inherit from it whenever you want.
Is there a situation where creating a class this way makes sense?
As others have said, it sounds like they really wanted a C# static class. VB's equivalent to "static" is "shared", but you can't mark classes "shared" in VB. The difference is that someone could inherit from this class and then create an instance. C# static classes are sealed.
What they should have done is use a Module. A VB Module and C# static class are virtually identical: members are associated with the type rather than an instance and you cannot inherit from them.
From an OO perspective, this doesn't make a lot of sense.
However, VB doesn't have a way to flag a class as Shared, like C# does. In C#, you'd likely flag this class as a static class - the MustInherit was most likely added to try to prevent people from creating an instance of it, even though it's basically a static class.
In C# a class can be declared as static (= Shared), and I think VB.NET doesn't allow that, so as a workaround it is marked abstract (MustInherit) so that it's never instantiated