This question already has answers here:
Can I extend a class using more than 1 class in PHP?
(18 answers)
Closed 2 years ago.
We know that PHP5 or later allow OOP but not support multiple inheritance like C++
Does PHP7 supported Multiple Inheritance?
From the manual:
A class can inherit the methods and properties of another class by
using the keyword extends in the class declaration. It is not possible
to extend multiple classes; a class can only inherit from one base
class.
I believe traits are a compromise to do things you'd usually do via multiple inheritance.
Traits are a mechanism for code reuse in single inheritance languages
such as PHP. A Trait is intended to reduce some limitations of single
inheritance by enabling a developer to reuse sets of methods freely in
several independent classes living in different class hierarchies. The
semantics of the combination of Traits and classes is defined in a way
which reduces complexity, and avoids the typical problems associated
with multiple inheritance and Mixins.
http://php.net/manual/en/language.oop5.traits.php
Or in a less nicer way, one class can keep extending another class which implements what you want Class B extends A {}, Class C extends B {}, etc
Related
This question already has answers here:
How should I denote static classes in UML?
(5 answers)
Closed 6 months ago.
I use a static class in my program code. does anyone know if you can mark static classes in a UML class diagram?
Edit
I have a static factory called CityMapFactory in C# that produces city maps. The city cards are objects that are given to a travel guide.
The C# static classes are classes that cannot be instantiated. Moreover
they are supposed to contain only static members and are sealed.
There is no static class in UML. But therer are all the tools necessesary:
A class that cannot be instantiated is generally called an abstract class in UML. This terminology is slightly different from some popular languages which bind this notion with the presence of abstract “methods” / “functions” / operations. Some may claim that a static class is not incomplete, however it misses a core feature that is necessary for normal classes: the means (constructors, implicit or explicit) that are needed to make it a normal class.
a class that is “sealed” is called a leaf class in UML. isLeaf is a property of classes in UML but there is no notation defined. U
Pragmatically {leaf} is used next to the class name (this notation was defined in some previous UML versions but no longer in the current one).
all members are static means that they should all be shown in underlined.
If you want to quickly show that you do not mean an abstract leaf class with all members being static by coincidence, you could create a special profile that could specify your own stereotype to clarify, e.g «static class», or use an existing C# profile (check if one is delivered with your favorite modeling tool before reinventing the wheel).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
After reading Interface vs Base class I understand that Inheritance should be used where there exists a "is-a" relationship and interfaces should be used in "can-do" kind of places.
If that means, base class can only have business objects and interfaces will have only the contracts?
For e.g Dog class will have a base class Animal with properties like Eye,Nose,Leg etc and interface IAnimal will have "Run", "Jump" etc.
Will design applicable for all the scenarios?
The answers on that question you linked actually say it all. Especially the accepted answer and its first comment. You use an interface to declare the contract and a base class for shared implementation.
I'd consider it a common practice to define interfaces for (almost) everything. An interface can also contain getters and setters and therefore define its subtypes properties. If two or more classes that implement that interface share some implementation, you can moved that to a base class. That base class would then also implement the interface.
Your understanding is correct, but I think it relies more on good practices than actual language rules. Please consider the following:
In languages that support multiple inheritance (C++) interfaces are just classes with all methods virtual and abstract. See this question
Languages that don't allow multiple inheritance (Java), the most important difference is that a class can have no more than 1 superclass, but can implement an arbitrary number of interfaces. There are also differences in declaring variables (variables are implicitly static and final in Java interfaces) but it's still not a big leap to think of interfaces as of 100% abstract classes.
Java 8 introduced default methods (see this question), which can kind of blur the obvious distinction between those two.
So while technically it's not true neither that interfaces must only define the contract (default methods can implement a fallback behavior in a Java 8 interface) nor that abstract classes must define behavior (because a pure abstract class with no implementations can exist), the approach that you described is kind of reasonable and common in real world.
It depends.....
That's a good starting point but it is not right to say that it will be applicable in all scenarios. Systems keep changing and as part of refactoring (http://refactoring.com/catalog/) sometimes interfaces become subclasses and the other way round. Interfaces are good for Mix-ins which you mention as "can-do" kind of behavior and Inheritance where a group of classes share certain properties and possibly some behavior enabling reuse and avoiding code duplication (which is essentially what a IS-A relationship is). You can read more about it in Effective Java by Joshua Bloch (there is an item on Interfaces and Inheritance).
If we take your example, the methods "Run" and "Jump" can be either defined in Animal base class or they can go in an interface as you mention, in fact they can actually go in multiple interfaces too. So you might start off by building a inheritance hierarchy and later refactor them into interfaces as the system evolves.
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.
While certain guidelines state that you should use an interface when you want to define a contract for a class where inheritance is not clear (IDomesticated) and inheritance when the class is an extension of another (Cat : Mammal, Snake : Reptile), there are cases when (in my opinion) these guidelines enter a gray area.
For example, say my implementation was Cat : Pet. Pet is an abstract class. Should that be expanded to Cat : Mammal, IDomesticated where Mammal is an abstract class and IDomesticated is an interface? Or am I in conflict with the KISS/YAGNI principles (even though I'm not sure whether there will be a Wolf class in the future, which would not be able to inherit from Pet)?
Moving away from the metaphorical Cats and Pets, let's say I have some classes that represent sources for incoming data. They all need to implement the same base somehow. I could implement some generic code in an abstract Source class and inherit from it. I could also just make an ISource interface (which feels more "right" to me) and re-implement the generic code in each class (which is less intuitive). Finally, I could "have the cake and eat it" by making both the abstract class and the interface. What's best?
These two cases bring up points for using only an abstract class, only an interface and using both an abstract class and an interface. Are these all valid choices, or are there "rules" for when one should be used over another?
I'd like to clarify that by "using both an abstract class and an interface" that includes the case when they essentially represent the same thing (Source and ISource both have the same members), but the class adds generic functionality while the interface specifies the contract.
Also worth noting is that this question is mostly for languages that do not support multiple inheritance (such as .NET and Java).
As a first rule of thumb, I prefer abstract classes over interfaces, based on the .NET Design Guidelines. The reasoning applies much wider than .NET, but is better explained in the book Framework Design Guidelines.
The main reasoning behind the preference for abstract base classes is versioning, because you can always add a new virtual member to an abstract base class without breaking existing clients. That's not possible with interfaces.
There are scenarios where an interface is still the correct choice (particularly when you don't care about versioning), but being aware of the advantages and disadvantages enables you to make the correct decision.
So as a partial answer before I continue: Having both an interface and a base class only makes sense if you decide to code against an interface in the first place. If you allow an interface, you must code against that interface only, since otherwise you would be violating the Liskov Substitution Principle. In other words, even if you provide a base class that implements the interface, you cannot let your code consume that base class.
If you decide to code against a base class, having an interface makes no sense.
If you decide to code against an interface, having a base class that provides default functionality is optional. It is not necessary, but may speed up things for implementers, so you can provide one as a courtesy.
An example that springs to mind is in ASP.NET MVC. The request pipeline works on IController, but there's a Controller base class that you typically use to implement behavior.
Final answer: If using an abstract base class, use only that. If using an interface, a base class is an optional courtesy to implementers.
Update: I no longer prefer abstract classes over interfaces, and I haven't for a long time; instead, I favour composition over inheritance, using SOLID as a guideline.
(While I could edit the above text directly, it would radically change the nature of the post, and since a few people have found it valuable enough to up-vote it, I'd rather let the original text stand, and instead add this note. The latter part of the post is still meaningful, so it would be a shame to delete it, too.)
I tend to use base classes (abstract or not) to describe what something is, while I use interfaces to describe the capabilities of an object.
A Cat is a Mammal but one of it's capabilities is that it is Pettable.
Or, to put it a different way, classes are nouns, while interfaces map closer to adjectives.
From MSDN, Recommendations for Abstract Classes vs. Interfaces
If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
If you want to provide the option of replacing your implementation completely, use an interface. This applies especially for interactions between major components, these should always be decoupled by interfaces.
There may also be technical reasons for prefering an interface, for example to enable mocking in unit tests.
Internally in a component it may be fine to just use an abstract class directly to access a hierarchy of classes.
If you use an interface and have a hierarchy of implementing classes then it is good practice to have an abstract classe which contain the common parts of the implementation. E.g.
interface Foo
abstract class FooBase implements Foo
class FunnyFoo extends FooBase
class SeriousFoo extends FooBase
You could also have more abstract classes inheriting from each other for a more complicated hierarchy.
Refer to below SE question for generic guidelines:
Interface vs Abstract Class (general OO)
Practical use case for interface:
Implementation of Strategy_pattern: Define your strategy as an interface. Switch the implementation dynamically with one of concrete implementations of strategy at run time.
Define a capability among multiple unrelated classes.
Practical use case for abstract class:
Implementation of Template_method_pattern: Define a skeleton of an algorithm. The child classes can't change strucutre of the algortihm but they can re-define a part of the implementation in child classes.
When you want share non-static and non-final variables among multiple related classes with "has a" relation.
Use of both abstradt class and interface:
If you are going for an abstract class, you can move abstract methods to interface and abstract class can simply implement that interface. All use cases of abstract classes can fall into this category.
I always use these guidelines:
Use interfaces for multiple TYPE inheritance (as .NET/Java don't use multiple inheritance)
Use abstract classes for a re-usable implementation of a type
The rule of the dominant concern dictates that a class always has a main concern and 0 or more others (see http://citeseer.ist.psu.edu/tarr99degrees.html). Those 0 or more others you then implement through interfaces, as the class then implements all the types it has to implement (its own, and all interfaces it implements).
In a world of multiple implementation inheritance (e.g. C++/Eiffel), one would inherit from classes which implement the interfaces. (In theory. In practise it might not work that well.)
There is also something called the DRY principle - Don't Repeat Yourself.
In your example of data sources you say there is some generic code that is common between different implementations. To me it seems that the best way to handle that would be to have an abstract class with the generic code in it and some concrete classes extending it.
The advantage is that every bug fix in generic code benefits all concrete implementations.
If you go interface only you will have to maintain several copies of the same code which is asking for trouble.
Regarding abstract + interface if there is no immediate justification for it I would not do it. Extracting interface from abstract class is an easy refactoring, so I would do it only when it is actually needed.
This question already has answers here:
Closed 13 years ago.
Duplicate:
When to use an interface instead of an abstract class and vice versa?
Probably one of the most famous software developer job interview questions.
What would be your answer?
EDIT: I'm trying to find out how you would answer this in a real-life situation. Please try to formulate your answer as you would on a real job interview (be complete, but don't be too long, post no links of course).
An interface only describes the actual signature of its methods etc. Any class implementing that interface must then provide an explicit implementation.
An abstract class can contain a partial implementation of its methods etc.
An abstract class can have member variables, an interface cannot (or, in C++, should not).
In Java, an "Interface" is a well-defined syntactical element, while in C++ it's merely a design pattern.
Interfaces provide definitions of methods that must be implemented by a class. The purpose of interfaces is to allow you to generalise specific functionality regardless of implementation. You may have an IDatabase interface that has an Open/Close method. The class that implements that interface may be connecting to a MySQL database or MS Access database. Irrespective of how it accomplishes this task, the goal is still the same...Open database, close database.
Abstract classes are base classes that contain some abstract methods. They cannot be instantiated they are to be derived from. The purpose of an Abstract class is to allow you to define some generic functionality and sub-class to implement more specific functionality where appropriate.
So in summary, you should use interfaces when the implementation of each class differs completely. Use abstract classes when you have some similar behaviour but need to implement parts differently.
Hope that helps.
I would say that the difference is language dependent, but that in C++ at least, abstract classes are the means by which interfaces are implemented.
As far as job interviews are concerned, I've always heard that the key point is that an interface is a contract; an interface, while not implementing it itself, guarantees functionality.