Why does Wikipedia say "Polymorphism is not the same as method overloading or method overriding." - oop

I have looked around and could not find any similar question.
Here is the paragraph I got from Wikipedia:
Polymorphism is not the same as method overloading or method overriding. Polymorphism is only concerned with the application of specific implementations to an interface or a more generic base class. Method overloading refers to methods that have the same name but different signatures inside the same class. Method overriding is where a subclass replaces the implementation of one or more of its parent's methods. Neither method overloading nor method overriding are by themselves implementations of polymorphism.
Could anyone here explain it more clearly, especially the part "Polymorphism is not the same as method overriding"? I am confused now. Thanks in advance.

Polymorphism (very simply said) is a possibility to use a derived class where a base class is expected:
class Base {
}
class Derived extends Base {
}
Base v = new Derived(); // OK
Method overriding, on the other hand, is as Wiki says a way to change the method behavior in a derived class:
class Shape {
void draw() { /* Nothing here, could be abstract*/ }
}
class Square extends Shape {
#Override
void draw() { /* Draw the square here */ }
}
Overloading is unrelated to inheritance, it allows defining more functions with the same name that differ only in the arguments they take.

You can have polymorphism in a language that does not allow method overriding (or even inheritance). e.g. by having several different objects implement the same interface. Polymorphism just means that you can have different concrete implementations of the same abstract interface. Some languages discourage or disallow inheritance but allow this kind of polymorphism in the spirit of programming with abstractions.
You could also theoretically have method overriding without polymorphism in a language that doesn't allow virtual method dispatch. The effect would be that you could create a new class with overridden methods, but you wouldn't be able to use it in place of the parent class. I'm not aware of any mainstream language that does this.

Polymorphism is not about methods being overridden; it is about the objects determining the implementation of a particular process. An easy example - but by no means the only example - is with inheritance:
A Novel is a type of Book. It has most of the same methods, and everything you can do to a Book can also be done to a Novel. Therefore, any method that accepts a Book as an argument can also deal with a Novel as an argument. (Example would include .read(), .write(), .burn()). This is, per se, not referring to the fact that a Novel can overwrite a Book method. Instead, it is referring to a feature of abstraction. If a professor assigns a Book to be read, he/she doesn't care how you read it - just that you do. Similarly, a calling program doesn't care how an object of type Book is read, just that it is. If the object is a Novel, it will be read as a Novel. If it is not a novel but is still a book, it will be read as a Book.
Book:
private void read(){
#Read the book.
}
Novel:
private void read(){
#Read a book, and complain about how long it is, because it's a novel!
}
Overloading methods is just referring to having two methods with the same name but a different number of arguments. Example:
writeNovel(int numPages, String name)
writeNovel(String name)

Overloading is having, in the same class, many methods with the same name, but differents parameters.
Overriding is having, in an inherited class, the same method+parameters of a base class. Thus, depending on the class of the object, either the base method, or the inherited method will be called.
Polymorphism is the fact that, an instance of an inherited class can replace an instance of a base class, when given as a parameters.
E.g. :
class Shape {
public void draw() {
//code here
}
public void draw(int size) {
//this is overloading
}
}
class Square inherits Shape {
public void draw() {
//some other code : this is overriding
}
public void draw(color c) {
//this is overloading too
}
}
class Work {
public myMethod(Shape s) {
//using polymophism, you can give to this method
//a Shape, but also a Square, because Square inherits Shape.
}
}
See it ?
Polymorphing is the fact that, the same object, can be used as an instance of its own class, its base class, or even as an interface.

Polymorphism refers to the fact that an instance of a type can be treated just like any instance of any of its supertypes. Polymorphism means 'many forms'.
Say you had a type named Dog. You then have a type named Spaniel which inherits from Dog. An instance of Spaniel can be used wherever a Dog is used - it can be treated just like any other Dog instance. This is polymorphism.
Method overriding is what a subclass may do to methods in a base class. Dog may contain a Bark method. Spaniel can override that method to provide a more specific implementation. Overriding methods does not affect polymorphism - the fact that you've overriden a Dog method in Spaniel does not enable you to or prevent you from treating a Spaniel like a dog.
Method overloading is simply the act of giving different methods which take different parameters the same name.
I hope that helps.

Frankly:
Polymorphism is using many types which have specific things in common in one implementation which only needs the common things, where as method overloading is using one implementation for each type.

When you override a method, you change its implementation. Polymorphism will use your implementation, or a base implementation, depending on your language (does it support virtual methods?) and depending on the class instance you've created.
Overloading a method is something else, it means using the same method with a different amount of parameters.
The combination of this (overriding), plus the possibility to use base classes or interfaces and still call an overriden method somewhere up the chain, is called polymorphism.
Example:
interface IVehicle
{
void Drive();
}
class Car : IVehicle
{
public Drive() { /* drive a car */ }
}
class MotorBike : IVehicle
{
public Drive() { /* drive a motorbike */ }
}
class Program
{
public int Main()
{
var myCar = new Car();
var myMotorBike = new MotorBike();
this.DriveAVehicle(myCar); // drive myCar
this.DriveAVehicle(myMotorBike); // drive a motobike
this.DriveAVhehicle(); // drive a default car
}
// drive any vehicle that implements IVehicle
// this is polymorphism in action
public DriveAVehicle(IVehicle vehicle)
{
vehicle.Drive();
}
// overload, creates a default car and drives it
// another part of OO, not directly related to polymorphism
public DriveAVehicle()
{
// typically, overloads just perform shortcuts to the method
// with the real implemenation, making it easier for users of the class
this.DriveAVehicle(new Car());
}
}

Related

Benefit of non-empty method of non-abstract class and abstract method of abstract method?

I don't understand why we use abstract method (abstract class) while we can use empty method of non-abstract class and then we override it. Does it sound fine? I am seeking to clarify this issue.
I give 2 examples
public abstract class MyClass {public abstract void foo();}
public MyChildClass extends MyClass {public void foo() {//..TODO}}
public class MyClass {public void foo(){//empty}}
public class MyChildClass extends MyClass {public void foo() {//..TODO}}
Which one is better?
I'll start by saying that you should try to use interfaces instead of abstract classes. Abstract classes couple the subclass to the implementation of the superclass. In a language like Java, the subclass can override any method even if the superclass did not intend to do so, and most people don't qualify their methods with "do not override" all the time.
At the lowest level, abstract methods give you two concrete protections at compile time:
They force you to override the method in a subclass
They disallow the creation of the abstract class
Before listing the use cases for abstract methods, I'll just say that "common functionality" is NOT a good reason for an abstract base class. If you need common functionality, just create a class that has the common methods, and let the various classes call these functions as they see fit.
So when would you use an abstract class? Here are some examples:
Template Method
In the template method pattern, you have all of your functionality, but there's just one internal aspect that's polymorphic, so you have subclasses that override that particular aspect.
For example, if you're implementing a cache, but the cache invalidation policy is polymorphic, you may have an abstract invalidate() method that is called internally by other methods, but it's up to subclasses to implement invalidate().
If there is a preferred default cache invalidation policy, then invalidate() could implement that default. But if that default is downright destructive in some cases, then it shouldn't be a default - it should be abstract, and the code that creates the cache should be forced to explicitly choose the invalidation policy.
This can also be achieved by passing an Invalidator class to the constructor (Strategy pattern), but if the invalidation logic needs to call methods of the cache, it's better to make those method protected and call them from a subclass (i.e. Template Method pattern).
Default implementation of other methods
In languages where interfaces cannot have default methods (e.g. Java 7), you can emulate it using abstract classes. All the interface methods will be abstract, but the default methods would be regular public methods.
Common Interface and Functionality
This is just a more generic version of the template method pattern. The difference is that the polymorphic methods are part of the API.
If your common functionality has a lot of overlap with the functionality you want to expose, and you don't want mountains of boilerplate code, you use an abstract class. For example:
interface File {
abstract Buffer read(int size);
abstract void write(Buffer buf);
abstract long getSize();
abstract void setSize();
// ... get/set creation time, get/set modification time, get
// file type etc.
abstract long getOwner();
abstract void setOwner(long owner);
}
abstract class AbstractFile extends File {
DataMap dataMap;
MetadataMap metaMap;
protected getDiskMap() { return dataMap; }
protected getMetaMap() { return metaMap; }
public Buffer read(int size) { /* loop here */ }
public void write(Buffer buf) { /* loop here */ }
public long getSize() { /* logic */ }
public void setSize() { /* logic */ }
// ... implementation of get/set creation time, get/set modification
// time, get file type etc.
}
abstract class HardDriveFile extends AbstractFile {
OwnershipMap ownerMap;
abstract long getOwner() { /* logic */ }
abstract void setOwner(long owner) { /* logic */ }
}
abstract class ThumbDriveFile extends AbstractFile {
// thumb drives have no ownership
abstract long getOwner() { return 0; }
abstract void setOwner(long owner) { /* no-op */ }
}
abstract class SomeOtherfile extends AbstractFile {
...
}
If we cut the middleman and have HardDriveFile and ThumbDriveFile (and possibly other types of files) implement File and spell out all the common methods, each calling a method of some common class, we would get mountains and mountains of boilerplate. So we inherit from an abstract base class, that has the abstract methods we want to specialize (e.g. based on the existence of an ownership map).
The naive thing to do would be to combine File and AbstractFile into a single class, which is where you'd get the abstract methods getOwner() and setOwner(), but it's better to hide abstract classes behind actual interfaces, to prevent the coupling between consumers of an API and the abstract class.

Benefits of an abstract class with a factory constructor?

I've recently run into some examples that make use of abstract classes as interfaces but also add factory constructors to the abstract interface so it can in a sense be "newed" up. For example:
abstract class WidgetService {
factory WidgetService() = ConcreteWidgetService;
Widget getWidget();
void saveWidget(Widget widget);
}
class ConcreteWidgetService extends BaseWidgetService implements WidgetService {
WidgetService();
Widget getWidget() {
// code to get widget here
}
void saveWidget(Widget widget) {
// code to save widget here
}
}
Usages of this service would be in some other service or component like so:
WidgetService _service = new WidgetService();
Based on my understanding of this sample, the line above would essentially "new" up a WidgetService, which usually produces an warning from the Dart analyzer, and said service variable would actually be an instance of ConcreateWidgetService based on the assignment of the ConcreateWidgetService to the factory constructor of the WidgetService.
Is there a benefit to this approach? From my OOP experience, I've used abstract classes/interfaces to program against when I didn't know the concrete type I would be given. Here it seems we are assigning the concrete type immediately to the abstract factory constructor. I guess my second question would be in this instance why not just use the ConcreteWidgetService directly here instead of repeating all the method signatures?
In your example the benefits are limited but in more complex situations the benefits become more clear.
A factory constructor allows you more control about what the constructor returns. It can return an instance of a subclass or an already existing (cached) instance.
It can return different concrete implementations based on a constructor parameter:
abstract class WidgetService {
WidgetService _cached;
factory WidgetService(String type) {
switch (type) {
case 'a':
return ConcreteWidgetServiceA();
case 'b':
return ConcreteWidgetServiceB();
default:
return _cached ??= DummyWidgetServiceA();
}
}
Widget getWidget();
void saveWidget(Widget widget);
}
Your example seems to be a preparation to be extended eventually to such a more flexible approach.
In Dart, all classes are also automatically interfaces. There's nothing strange about creating a instance of - 'newing up' - an 'interface', because it's actually just creating an instance of a class.
The purpose of some abstract classes is specifically to define an interface, but they have factory constructors that return a 'default implementation' of themselves.
For instance:
void main() {
var v = new Map();
print(v.runtimeType);
}
prints: _InternalLinkedHashMap - the (current) default implementation of Map.
Core library users can create and using instances of Map without knowing or caring about the implementation they actually get. The library authors may change the implementation without breaking anyone's code.
Of course, other classes may implement Map also.
With respect to your code sample, WidgetService _service = new WidgetService(); does not produce an analyzer warning. See this example on DartPad (Note I fixed a couple of errors in your sample).
I was initially confused by:
factory WidgetService() = ConcreteWidgetService;
instead of:
factory WidgetService() => new ConcreteWidgetService();
but it seems to work.

Multiple Inheritance: What's a good example?

I'm trying to find a good example for the use of multiple inheritance what cannot be done with normal interfaces.
I think it's pretty hard to find such an example which cannot be modeled in another way.
Edit: I mean, can someone name me a good real-world example of when you NEED to use multiple inheritance to implement this example as clean as possible. And it should not make use of multiple interfaces, just the way you can inherit multiple classes in C++.
The following is a classic:
class Animal {
public:
virtual void eat();
};
class Mammal : public Animal {
public:
virtual void breathe();
};
class WingedAnimal : public Animal {
public:
virtual void flap();
};
// A bat is a winged mammal
class Bat : public Mammal, public WingedAnimal {
};
Source: wiki.
One example where multiple class inheritance makes sense is the Observer pattern. This pattern describes two actors, the observer and the observable, and the former wants to be notified when the latter changes its object state.
A simplified version for notifying clients can look like this in C#:
public abstract class Observable
{
private readonly List<IObserver> _observers = new List<IObserver>();
// Objects that want to be notified when something changes in
// the observable can call this method
public void Subscribe(IObserver observer)
{
_observers.Add(observer);
}
// Subclasses can call this method when something changes
// to notify all observers
protected void Notify()
{
foreach (var observer in _observers)
observer.Notify();
}
}
This basically is the core logic you need to notify all the registered observers. You could make any class observable by deriving from this class, but as C# does only support single class inheritance, you are limited to not derive from another class. Something like this wouldn't work:
public class ImportantBaseClass { /* Members */ }
public class MyObservableSubclass : ImportantBaseClass, Observable { /* Members */ }
In these cases you often have to replicate the code that makes subclasses observable in all of them, basically violating the Don't Repeat Yourself and the Single Point of Truth principles (if you did MVVM in C#, think about it: how often did you implement the INotifyPropertyChanged interface?). A solution with multiple class inheritance would be much cleaner in my opinion. In C++, the above example would compile just fine.
Uncle Bob wrote an interesting article about this, that is where I got the example from. But this problem often applies to all interfaces that are *able (e.g. comparable, equatable, enumerable, etc.): a multiple class inheritance version is often cleaner in these cases, as stated by Bertrand Meyer in his book "Object-Oriented Software Construction".

Bridge Pattern - Composition or Aggregation?

I'm reading some books about Design Patterns and while some describe the relation between the abstraction and the implementation as a composition, some describe it as an aggregation. Now I wonder: is this dependant on the implementation? On the language? Or context?
The terms "composition" and "aggregation" mean more or less the same thing and may be used interchangeably. Aggregation may be used more frequently when describing container classes such as lists, dynamic arrays, maps, and queues where the elements are all of the same type; however, both terms may be found to describe classes defined in terms of other classes, regardless of whether those types are homogenous (all of the same type) or heterogenous (objects of different types).
To make this clearer:
class Car {
// ...
private:
Engine engine;
Hood hood;
};
// The car is *composed* of an engine and a hood. Hence, composition. You are
// also bringing together (i.e. *aggregating*) an engine and hood into a car.
The relationship between abstraction and implementation typically implies inheritance, rather than composition/aggregation; typically the abstraction is an interface or virtual base class, and the implementation is a fully concrete class that implements the given interface. But, to make things confusing, composition/aggregation can be a part of the interface (because, for example, you may need to set/get the objects that are used as building blocks), and they are also an approach to implementation (because you might use delegation to provide the definition for methods in your implementation).
To make this clearer:
interface Car {
public Engine getEngine();
public Hood getHood();
public void drive();
}
// In the above, the fact that a car has these building blocks
// is a part of its interface (the abstraction).
class HondaCivic2010 implements Car {
public void drive(){ getEngine().drive(); }
// ...
}
// In the above, composition/delegation is an implementation
// strategy for providing the drive functionality.
Since you have tagged your question "bridge", I should point out that the definition of the bridge pattern is a pattern where you use composition rather than inheritance to allow for variation at multiple different levels. An example that I learned at college... using inheritance you might have something like:
class GoodCharacter;
class BadCharacter;
class Mage;
class Rogue;
class GoodMage : public GoodCharacter, Mage;
class BadMage : public BadCharacter, Mage;
class GoodRogue : public GoodCharacter, Rogue;
class BadRogue : public BadCharacter, Rogue;
As you can see, this kind of thing goes pretty crazy, and you get a ridiculous number of classes. The same thing, with the bridge pattern, would look like:
class Personality;
class GoodPersonality : public Personality;
class BadPersonality : public Personality;
class CharacterClass;
class Mage : public CharacterClass;
class Rogue : public CharacterClass;
class Character {
public:
// ...
private:
CharacterClass character_class;
Personality personality;
};
// A character has both a character class and a personality.
// This is a perfect example of the bridge pattern, and we've
// reduced MxN classes into a mere M+N classes, and we've
// arguably made the system even more flexible than before.
the bridge pattern must use delegation (aggregation/composition and not inheritance). from the gang-of-four book:
Use the Bridge pattern when
* you want to avoid a permanent binding between an abstraction and its implementation. This might be the case, for example, when the implementation must be selected or switched at run-time.
* both the abstractions and their implementations should be extensible by subclassing. In this case, the Bridge pattern lets you combine the different abstractions and implementations and extend them independently.
* changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled.
* (C++) you want to hide the implementation of an abstraction completely from clients. In C++ the representation of a class is visible in the class interface.
* you have a proliferation of classes as shown earlier in the first Motivation diagram. Such a class hierarchy indicates the need for splitting an object into two parts. Rumbaugh uses the term "nested generalizations" [RBP+91] to refer to such class hierarchies.
* you want to share an implementation among multiple objects (perhaps using reference counting), and this fact should be hidden from the client. A simple example is Coplien's String class [Cop92], in which multiple objects can share the same string representation (StringRep).
Standard UML of Bridge pattern clears out all air around the confusion. Below is an explanation with a brief example to clear the air around this.
Apologies for this lengthy code, best way is to copy this code to Visual Studio to easily understand it.
Read through the explanation written at the end of code
interface ISpeak
{
void Speak();
}
class DogSpeak : ISpeak
{
public void Speak()
{
Console.WriteLine("Dog Barks");
}
}
class CatSpeak : ISpeak
{
public void Speak()
{
Console.WriteLine("Cat Meows");
}
}
abstract class AnimalBridge
{
protected ISpeak Speech;
protected AnimalBridge(ISpeak speech)
{
this.Speech = speech;
}
public abstract void Speak();
}
class Dog : AnimalBridge
{
public Dog(ISpeak dogSpeak)
: base(dogSpeak)
{
}
public override void Speak()
{
Speech.Speak();
}
}
class Cat : AnimalBridge
{
public Cat(ISpeak catSpeak)
: base(catSpeak)
{
}
public override void Speak()
{
Speech.Speak();
}
}
-- ISpeak is the abstraction that bot Dog and Cat has to implement
-- Decoupled Dog and Cat classes by introducing a bridge "Animal" that is composed of ISpeak
-- Dog and Cat classes extend Animal class and thus are decoupled from ISpeak.
Hope this clarifies

What is the use of making constructor private in a class?

Why should we make the constructor private in class? As we always need the constructor to be public.
Some reasons where you may need private constructor:
The constructor can only be accessed from static factory method inside the class itself. Singleton can also belong to this category.
A utility class, that only contains static methods.
By providing a private constructor you prevent class instances from being created in any place other than this very class. There are several use cases for providing such constructor.
A. Your class instances are created in a static method. The static method is then declared as public.
class MyClass()
{
private:
MyClass() { }
public:
static MyClass * CreateInstance() { return new MyClass(); }
};
B. Your class is a singleton. This means, not more than one instance of your class exists in the program.
class MyClass()
{
private:
MyClass() { }
public:
MyClass & Instance()
{
static MyClass * aGlobalInst = new MyClass();
return *aGlobalInst;
}
};
C. (Only applies to the upcoming C++0x standard) You have several constructors. Some of them are declared public, others private. For reducing code size, public constructors 'call' private constructors which in turn do all the work. Your public constructors are thus called delegating constructors:
class MyClass
{
public:
MyClass() : MyClass(2010, 1, 1) { }
private:
MyClass(int theYear, int theMonth, int theDay) { /* do real work */ }
};
D. You want to limit object copying (for example, because of using a shared resource):
class MyClass
{
SharedResource * myResource;
private:
MyClass(const MyClass & theOriginal) { }
};
E. Your class is a utility class. That means, it only contains static members. In this case, no object instance must ever be created in the program.
To leave a "back door" that allows another friend class/function to construct an object in a way forbidden to the user. An example that comes to mind would be a container constructing an iterator (C++):
Iterator Container::begin() { return Iterator(this->beginPtr_); }
// Iterator(pointer_type p) constructor is private,
// and Container is a friend of Iterator.
Everyone is stuck on the Singleton thing, wow.
Other things:
Stop people from creating your class on the stack; make private constructors and only hand back pointers via a factory method.
Preventing creating copys of the class (private copy constructor)
This can be very useful for a constructor that contains common code; private constructors can be called by other constructors, using the 'this(...);' notation. By making the common initialization code in a private (or protected) constructor, you are also making explicitly clear that it is called only during construction, which is not so if it were simply a method:
public class Point {
public Point() {
this(0,0); // call common constructor
}
private Point(int x,int y) {
m_x = x; m_y = y;
}
};
There are some instances where you might not want to use a public constructor; for example if you want a singleton class.
If you are writing an assembly used by 3rd parties there could be a number of internal classes that you only want created by your assembly and not to be instantiated by users of your assembly.
This ensures that you (the class with private constructor) control how the contructor is called.
An example : A static factory method on the class could return objects as the factory method choses to allocate them (like a singleton factory for example).
We can also have private constructor,
to enfore the object's creation by a specific class
only(For security reasons).
One way to do it is through having a friend class.
C++ example:
class ClientClass;
class SecureClass
{
private:
SecureClass(); // Constructor is private.
friend class ClientClass; // All methods in
//ClientClass have access to private
// & protected methods of SecureClass.
};
class ClientClass
{
public:
ClientClass();
SecureClass* CreateSecureClass()
{
return (new SecureClass()); // we can access
// constructor of
// SecureClass as
// ClientClass is friend
// of SecureClass.
}
};
Note: Note: Only ClientClass (since it is friend of SecureClass)
can call SecureClass's Constructor.
You shouldn't make the constructor private. Period. Make it protected, so you can extend the class if you need to.
Edit: I'm standing by that, no matter how many downvotes you throw at this.
You're cutting off the potential for future development on the code. If other users or programmers are really determined to extend the class, then they'll just change the constructor to protected in source or bytecode. You will have accomplished nothing besides to make their life a little harder. Include a warning in your constructor's comments, and leave it at that.
If it's a utility class, the simpler, more correct, and more elegant solution is to mark the whole class "static final" to prevent extension. It doesn't do any good to just mark the constructor private; a really determined user may always use reflection to obtain the constructor.
Valid uses:
One good use of a protected
constructor is to force use of static
factory methods, which allow you to
limit instantiation or pool & reuse
expensive resources (DB connections,
native resources).
Singletons (usually not good practice, but sometimes necessary)
when you do not want users to create instances of this class or create class that inherits this class, like the java.lang.math, all the function in this package is static, all the functions can be called without creating an instance of math, so the constructor is announce as static.
If it's private, then you can't call it ==> you can't instantiate the class. Useful in some cases, like a singleton.
There's a discussion and some more examples here.
I saw a question from you addressing the same issue.
Simply if you don't want to allow the others to create instances, then keep the constuctor within a limited scope. The practical application (An example) is the singleton pattern.
Constructor is private for some purpose like when you need to implement singleton or limit the number of object of a class.
For instance in singleton implementation we have to make the constructor private
#include<iostream>
using namespace std;
class singletonClass
{
static int i;
static singletonClass* instance;
public:
static singletonClass* createInstance()
{
if(i==0)
{
instance =new singletonClass;
i=1;
}
return instance;
}
void test()
{
cout<<"successfully created instance";
}
};
int singletonClass::i=0;
singletonClass* singletonClass::instance=NULL;
int main()
{
singletonClass *temp=singletonClass::createInstance();//////return instance!!!
temp->test();
}
Again if you want to limit the object creation upto 10 then use the following
#include<iostream>
using namespace std;
class singletonClass
{
static int i;
static singletonClass* instance;
public:
static singletonClass* createInstance()
{
if(i<10)
{
instance =new singletonClass;
i++;
cout<<"created";
}
return instance;
}
};
int singletonClass::i=0;
singletonClass* singletonClass::instance=NULL;
int main()
{
singletonClass *temp=singletonClass::createInstance();//return an instance
singletonClass *temp1=singletonClass::createInstance();///return another instance
}
Thanks
You can have more than one constructor. C++ provides a default constructor and a default copy constructor if you don't provide one explicitly. Suppose you have a class that can only be constructed using some parameterized constructor. Maybe it initialized variables. If a user then uses this class without that constructor, they can cause no end of problems. A good general rule: If the default implementation is not valid, make both the default and copy constructor private and don't provide an implementation:
class C
{
public:
C(int x);
private:
C();
C(const C &);
};
Use the compiler to prevent users from using the object with the default constructors that are not valid.
Quoting from Effective Java, you can have a class with private constructor to have a utility class that defines constants (as static final fields).
(EDIT: As per the comment this is something which might be applicable only with Java, I'm unaware if this construct is applicable/needed in other OO languages (say C++))
An example as below:
public class Constants {
private Contants():
public static final int ADDRESS_UNIT = 32;
...
}
EDIT_1:
Again, below explanation is applicable in Java : (and referring from the book, Effective Java)
An instantiation of utility class like the one below ,though not harmful, doesn't serve
any purpose since they are not designed to be instantiated.
For example, say there is no private Constructor for class Constants.
A code chunk like below is valid but doesn't better convey intention of
the user of Constants class
unit = (this.length)/new Constants().ADDRESS_UNIT;
in contrast with code like
unit = (this.length)/Constants.ADDRESS_UNIT;
Also I think a private constructor conveys the intention of the designer of the Constants
(say) class better.
Java provides a default parameterless public constructor if no constructor
is provided, and if your intention is to prevent instantiation then a private constructor is
needed.
One cannot mark a top level class static and even a final class can be instantiated.
Utility classes could have private constructors. Users of the classes should not be able to instantiate these classes:
public final class UtilityClass {
private UtilityClass() {}
public static utilityMethod1() {
...
}
}
You may want to prevent a class to be instantiated freely. See the singleton design pattern as an example. In order to guarantee the uniqueness, you can't let anyone create an instance of it :-)
One of the important use is in SingleTon class
class Person
{
private Person()
{
//Its private, Hense cannot be Instantiated
}
public static Person GetInstance()
{
//return new instance of Person
// In here I will be able to access private constructor
}
};
Its also suitable, If your class has only static methods. i.e nobody needs to instantiate your class
It's really one obvious reason: you want to build an object, but it's not practical to do it (in term of interface) within the constructor.
The Factory example is quite obvious, let me demonstrate the Named Constructor idiom.
Say I have a class Complex which can represent a complex number.
class Complex { public: Complex(double,double); .... };
The question is: does the constructor expects the real and imaginary parts, or does it expects the norm and angle (polar coordinates) ?
I can change the interface to make it easier:
class Complex
{
public:
static Complex Regular(double, double = 0.0f);
static Complex Polar(double, double = 0.0f);
private:
Complex(double, double);
}; // class Complex
This is called the Named Constructor idiom: the class can only be built from scratch by explicitly stating which constructor we wish to use.
It's a special case of many construction methods. The Design Patterns provide a good number of ways to build object: Builder, Factory, Abstract Factory, ... and a private constructor will ensure that the user is properly constrained.
In addition to the better-known uses…
To implement the Method Object pattern, which I’d summarize as:
“Private constructor, public static method”
“Object for implementation, function for interface”
If you want to implement a function using an object, and the object is not useful outside of doing a one-off computation (by a method call), then you have a Throwaway Object. You can encapsulate the object creation and method call in a static method, preventing this common anti-pattern:
z = new A(x,y).call();
…replacing it with a (namespaced) function call:
z = A.f(x,y);
The caller never needs to know or care that you’re using an object internally, yielding a cleaner interface, and preventing garbage from the object hanging around or incorrect use of the object.
For example, if you want to break up a computation across methods foo, bar, and zork, for example to share state without having to pass many values in and out of functions, you could implement it as follows:
class A {
public static Z f(x, y) {
A a = new A(x, y);
a.foo();
a.bar();
return a.zork();
}
private A(X x, Y y) { /* ... */ };
}
This Method Object pattern is given in Smalltalk Best Practice Patterns, Kent Beck, pages 34–37, where it is the last step of a refactoring pattern, ending:
Replace the original method with one that creates an instance of the new class, constructed with the parameters and receiver of the original method, and invokes “compute”.
This differs significantly from the other examples here: the class is instantiable (unlike a utility class), but the instances are private (unlike factory methods, including singletons etc.), and can live on the stack, since they never escape.
This pattern is very useful in bottoms-up OOP, where objects are used to simplify low-level implementation, but are not necessarily exposed externally, and contrasts with the top-down OOP that is often presented and begins with high-level interfaces.
Sometimes is useful if you want to control how and when (and how many) instances of an object are created.
Among others, used in patterns:
Singleton pattern
Builder pattern
On use of private constructors could also be to increase readability/maintainability in the face of domain-driven design.
From "Microsoft .NET - Architecing Applications for the Enterprise, 2nd Edition":
var request = new OrderRequest(1234);
Quote, "There are two problems here. First, when looking at the code, one can hardly guess what’s going
on. An instance of OrderRequest is being created, but why and using which data? What’s 1234? This
leads to the second problem: you are violating the ubiquitous language of the bounded context. The
language probably says something like this: a customer can issue an order request and is allowed to
specify a purchase ID. If that’s the case, here’s a better way to get a new OrderRequest instance:"
var request = OrderRequest.CreateForCustomer(1234);
where
private OrderRequest() { ... }
public OrderRequest CreateForCustomer (int customerId)
{
var request = new OrderRequest();
...
return request;
}
I'm not advocating this for every single class, but for the above DDD scenario I think it makes perfect sense to prevent a direct creation of a new object.
If you create a private constructor you need to create the object inside the class
enter code here#include<iostream>
//factory method
using namespace std;
class Test
{
private:
Test(){
cout<<"Object created"<<endl;
}
public:
static Test* m1(){
Test *t = new Test();
return t;
}
void m2(){
cout<<"m2-Test"<<endl;
}
};
int main(){
Test *t = Test::m1();
t->m2();
return 0;
}