I have some classes in c++. with some hierarchy of base class and some derived classes.
There are some methods in the some derived classes that does functionality for that particular derived class and the other classes do not need any implementation of those methods. So i left them as empty implementation. (All of these functions are virtual)
Now my question is that what are the best practices in OOP while calling such a method with base class pointer in your program. I mean first check the type of reference stored in the base class pointer and then call the method or call the method in any way as the implementation of that particular method in other classes in empty.
In C++, run-time polymorphism is achieved through virtual functions. More info
Related
I understand that Abstract Classes are classes that contain declared methods that do not all necessarily have a specified implementation because the code would have to be declared in the child class instead but Im finding it difficult to understand the OOP concept behind the introduction of Interfaces.
What are the architectural and principle differences between interfaces and abstract classes if the abstract class has no defined methods and states (Aside from the fact that abstract classes can have constructors)?
In addition, why should anyone use abstract classes and interfaces in the first place? I understand that it adds restrictions to your code not allowing people to defined subclasses without specified methods but the code would work in the exact same way if the non implemented declared methods were not present in the interface and abstract class. So what is the implied benefit of writing methods with no implementation only to implement it later in the subclass?
I have seen many posts on Interface vs Abstract Classes but im interested in the principle differences between the two, not their functional differences.
Coming back to my own question after a year, I have discovered the answer that I wanted.
A class, regardless of being abstract or not, always tries to define/design what entities look like from their behaviour to their states. In the case of an abstract class, we are modelling an idea/entity that we do not want to be instantiated during run time. Example, if we had an app about dogs and cats, we may want to define what an animal is and then extend this idea to define what a dog/cat is by extending our base animal class. An animal object will never be instantiated but a dog/cat will.
An interface on the other hand are a set of methods that represents some form of interactions to be expected from any class. As long as a class implements an interface, you know what methods to expect from it. Thus, you can have two entities (classes) that do not relate to one another that implement the same interface. Example, a dog and person class may both implement a 'digest' interface. This means that they are all able to digest food as we have explicitly stated what functions to expect in the interface to enable food digestion behaviour. Obviously the details of the implementation differs thus the functions defined in the interface are outlined in the classes implementing them.
In OOP we don't want coupling of classes. If I want to use an instance of class b within class a I can use dependency injection.
However if I want to use static methods of class b within class a I dont see any option but to "require" or "import" class b in the class a class file. This ends up with coupling between the classes - going against OOP principles. But the alternative is to rewrite the static method of class b as a static method in class a - going against the DRY principle. What is the right way?
This question was flagged as a possible duplicate of How to use Dependency Injection with Static Methods? but I feel that my question is asking from a more generic perspective on using another class' static methods. The think the question and accepted answer in the possible duplicate is more specific to a use case, but would not apply for example to a mere utility static method in the external class. My question aims to seek answer from a general oop perspective.
There are a variety options here and the specific use case is important in deciding what you may want to do. So, the big three would be...
Migrate the static method off Class B and into a shared library class, which is purely a holder for static methods and is never instantiated (in Java you'd make the constructor private and the class final). Then both class A and class B can access the method without depending on each other and without violating the DRY principle and the dependency on the library class is no better nor worse than relying on a static method defined on the same class.
If you're talking about a static method which is really something that best lives on class B then you can hide that method call behind some kind of a provider instance which is dependency injected into class A, with the provider implementation simply calling the static method on B. If you wanted to be really evil then the provider could also be injected into instances of B, but that would probably be overkill.
The static method can be changed to be an instance method on a new class which is dependency injected into both A and B. Sometimes this has a side-benefit of allowing you to hide some state in the instance rather than having to pass parameters into an otherwise stateless method.
Note that static methods in general cause problems in OO terms so only really the third options is a 'clean' one that really decouples classes and properly allow for coding to interfaces.
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.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Interface vs Abstract Class (general OO)
What are the differences and similarities between an interface class and an abstract class?
I mean when to use interface and when to use abstract class? On what conditions are one appropriate to use over another.
First off, an interface is not a class. An interface cannot specify functionality but rather only the required names of things.
An interface defines what methods and properties must be publicly available in any class that inherits from the interface. An interface contains no implementation code and says nothing about any non-public aspects of the class. An interface is not a class but rather more of a contract.
An abstract class is a real class. The unique restriction of an abstract class is that it cannot be instantiated directly. Rather, you have to instantiate a subclass that inherits from the abstract class.
As to when to use them, I would say that you should consider inheriting from an abstract class when your objects really share a common ancestor. For example, it would be logical if 'salesman' and 'programmer' both inherited from an abstract 'employee' class.
Interfaces are useful when you want to know what the public interface of a class will look like but you do not require that they share any commonality in terms of implementation. For example, in C# any class that implements the IEnumerable interface can be iterated over and will certainly implement MoveNext and Current. This could be a collection like a list or an array or it could be a generator (state-machine) that calls into a database or a web service or even generates random numbers. The implementations of IEnumerable do not need to share any common code at all other than the names of methods and properties specified in the interface.
It is worth noting that, in C#, you can only inherit from a single class but you can implement as many interfaces as you like. Also, in C# interfaces begin with a captial 'I' by convention but strictly speaking this is not required.
I have seen many answers on stackoverflow, but I didn't find an answer that is matching mine.
Apart from all those difference, Does it make sense if we say an abstract class abstracts the implementation of behaviour while an interface abstracts the type which implements the behaviour.
An abstract class can (and normally does) provide some implementation.
And interface cannot provide any implementation.
The main differences from design point of view are that:
you can declare a contract on constructor of the implementing classes, by creating a protected constructor in the base abstract class.
you can provide implementations of methods usable by base classes
you can make a wrapper around the contract (e.g. validate method arguments)
you can provide a "calling scheme" when you create non-abstract methods that call abstract methods of the type, implemented by derived classes. This can be useful for implementing abstraction of an algorithm in derived classes, while the base class implements all the handling logic - prepares and validates data, and lets the actual processing algorithm to be implemented by derived classes.
So I would say you are correct in the statement that "an abstract class abstracts the implementation of behaviour while an interface abstracts the type which implements the behaviour"
Abstract class: provides requirement to implement some methods (you override methods of the abstract class)
Interface: defines only a contract. Indicates that a class that implements the interface has methods of the interface (you implement an interface)
For example:
by implementing an interface on an existing class, you just declare adding the interface methods to the contract of the class. The class may already implement all the methods of the interface and you do not need to change anything in the existing class.
by changing the base type to an abstract class, you are required to override all the methods, even if methods with the same names as abstract methods of the base class already exist on the type.
Not really no, because an abstract class doesn't need to implement any behaviour. It probably should, because otherwise you may argue the usefulness of it, but it doesn't have to.
Commonly, an abstract class implements some behavior, but leaves some specialized behavior unimplemented.
For example, you might write a class that implements a network application server, but does not implement the process function, instead leaving that to the inherited class to implement.
class MyServer(Networkserver):
// process() is called whenever a client has sent a request
function process(data):
...
By making the class abstract and therefore unable to be instantiated, there does not have to be some proper "default" behavior for the specialization functions.
Interface = pure abstract class (abstract class with no implementation)
Purely from a design point of view, and being language agnostic, an interface is a contract between your class and the client, promising what it does, not how it does it. This is the usage implied in the "program to an interface" mantra.
Since languages such as C++ don't have interfaces, an abstract class is the only way to represent it. For languages in which interface is a first class construct, either way is acceptable and there are trade-offs in the choice. There are, of course, other technical differences in implementation between languages, but I don't believe you asked about those.
There is an interview with Erich Gamma, in which he discusses some of the differences.
To answer your question, I think it makes sense from a theoretical point of view. From a practical point of view, it probably depends which language you are programming in :)
Both have specific uses as per the language design- abstract class are designed to be a base class and cannot be instantiated. wheras when u need to define just a contract (NO implementation) which each implementing class must follow in thrie own way, then u must use interfaces.Also -
Can be a base class for Inheritance
abstract class - yes Interface - no
Can have impelementation
abstract class - Yes Interface -No