How to wrap my head around Object Oriented Design - java

Object oriented design is a pretty neat concept, but I'm struggling on how to wrap my head around most of its facets. I think the key to a good object oriented design is having a good grasp on how to look at it. I usually look at object-oriented this way:
Classes are Real-world entities or objects
Instance Fields are entity's attributes, ('has A')
Methods are like actions, verbs, Entity's abilities
Interfaces are like abilities that you can imbue on an object. It could also be an 'is A or can do' relationship whose implementations are not set in stone. Superman is a Krypton, being a Kryptonian comes with a set of special abilities, like flying, freeze-breath, etc. Superman fly different from Green Lantern and Goku and especially Batman, that is why Flight as interface is probably a good idea if you're creating a Fictional Universe.
public class SuperMan extends Man implements Kryptonian{}
public interface Kryptonian extends Flight, FreezeBreath{
public void fly();
public void coolBreath();
}
Problem comes along when you add Generics into the mix? Because the given type parameters somehow creates a contract between the class/interface and the type.
public interface Flight<T>{
public void fly(T t);
}
In this example, Flight is coupled with a T, T could be a superhero a bird or anything that can fly.But is that really how I should imagine it? Because that seems like the same as what plain interfaces do? Although, a parameterized interface is still an interface, the coupling with the type T is what really bothers me. Moreover, things also get complicated when you add bounded restriction on the parameter type.
public class Pidgey<T extends Bird> implements Flight<T>{}
what real-world concrete object can you identify T with? The above example is pretty wrong, although using the class parameter to also restrict the type of Flight is probably a good design, because Flight is still independent enough that other classes could still use it without any restriction. But the example itself is wrong. Pidgey is a Bird that can fly, but what what could T be? Well, T could be anything, it could be another object or abilities. The question is what are its implications, why put T there? What are real-world examples of doing so?
It's easy to understand when you talk about collections, since collections are like containers. You can create a wide variety of containers that holds different kinds of objects.
public class WaterBottle<T extends Liquid> implements UniqueCap{}
But I've seen Generics being used not just on a container-like objects? How could one design such objects, what did they consider?

Your analogies to the various features in OOP are definitely valid. Generics definitely make the most sense when talking about collections/containers/Hashmaps. They do have their uses in other places, though. For example, if a bank wants to process notes in many currencies, they can write
public class moneyProcessor
However, generics aren't required. In the context of your Flight interface, there wouldn't be much of a reason to use generics. Which brings me to another point:
Just because someone else does something one way doesn't mean you have to do it that way. OOP is very flexible for a reason. There's always more than one correct way. If a method takes an Object as a parameter, it's not the end of the world. Just make sure you can read it later. :)
Edit: and that others can read it too.

Its convention to use T when dealing with generics. it makes code readable as others reading your code will immediately know you're referring to a generic and nothing specific

Related

Why would I use extension over an instance and vice versa? [duplicate]

Why prefer composition over inheritance? What trade-offs are there for each approach? When should you choose inheritance over composition?
Prefer composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach. With composition, it's easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type. So the goose is more or less cooked once you derive from TypeA.
My acid test for the above is:
Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates Inheritance.
e.g. A Cessna biplane will expose the complete interface of an airplane, if not more. So that makes it fit to derive from Airplane.
Does TypeB want only some/part of the behavior exposed by TypeA? Indicates need for Composition.
e.g. A Bird may need only the fly behavior of an Airplane. In this case, it makes sense to extract it out as an interface / class / both and make it a member of both classes.
Update: Just came back to my answer and it seems now that it is incomplete without a specific mention of Barbara Liskov's Liskov Substitution Principle as a test for 'Should I be inheriting from this type?'
Think of containment as a has a relationship. A car "has an" engine, a person "has a" name, etc.
Think of inheritance as an is a relationship. A car "is a" vehicle, a person "is a" mammal, etc.
I take no credit for this approach. I took it straight from the Second Edition of Code Complete by Steve McConnell, Section 6.3.
If you understand the difference, it's easier to explain.
Procedural Code
An example of this is PHP without the use of classes (particularly before PHP5). All logic is encoded in a set of functions. You may include other files containing helper functions and so on and conduct your business logic by passing data around in functions. This can be very hard to manage as the application grows. PHP5 tries to remedy this by offering a more object-oriented design.
Inheritance
This encourages the use of classes. Inheritance is one of the three tenets of OO design (inheritance, polymorphism, encapsulation).
class Person {
String Title;
String Name;
Int Age
}
class Employee : Person {
Int Salary;
String Title;
}
This is inheritance at work. The Employee "is a" Person or inherits from Person. All inheritance relationships are "is-a" relationships. Employee also shadows the Title property from Person, meaning Employee.Title will return the Title for the Employee and not the Person.
Composition
Composition is favoured over inheritance. To put it very simply you would have:
class Person {
String Title;
String Name;
Int Age;
public Person(String title, String name, String age) {
this.Title = title;
this.Name = name;
this.Age = age;
}
}
class Employee {
Int Salary;
private Person person;
public Employee(Person p, Int salary) {
this.person = p;
this.Salary = salary;
}
}
Person johnny = new Person ("Mr.", "John", 25);
Employee john = new Employee (johnny, 50000);
Composition is typically "has a" or "uses a" relationship. Here the Employee class has a Person. It does not inherit from Person but instead gets the Person object passed to it, which is why it "has a" Person.
Composition over Inheritance
Now say you want to create a Manager type so you end up with:
class Manager : Person, Employee {
...
}
This example will work fine, however, what if Person and Employee both declared Title? Should Manager.Title return "Manager of Operations" or "Mr."? Under composition this ambiguity is better handled:
Class Manager {
public string Title;
public Manager(Person p, Employee e)
{
this.Title = e.Title;
}
}
The Manager object is composed of an Employee and a Person. The Title behaviour is taken from Employee. This explicit composition removes ambiguity among other things and you'll encounter fewer bugs.
With all the undeniable benefits provided by inheritance, here's some of its disadvantages.
Disadvantages of Inheritance:
You can't change the implementation inherited from super classes at runtime (obviously because inheritance is defined at compile time).
Inheritance exposes a subclass to details of its parent class implementation, that's why it's often said that inheritance breaks encapsulation (in a sense that you really need to focus on interfaces only not implementation, so reusing by sub classing is not always preferred).
The tight coupling provided by inheritance makes the implementation of a subclass very bound up with the implementation of a super class that any change in the parent implementation will force the sub class to change.
Excessive reusing by sub-classing can make the inheritance stack very deep and very confusing too.
On the other hand Object composition is defined at runtime through objects acquiring references to other objects. In such a case these objects will never be able to reach each-other's protected data (no encapsulation break) and will be forced to respect each other's interface. And in this case also, implementation dependencies will be a lot less than in case of inheritance.
Another, very pragmatic reason, to prefer composition over inheritance has to do with your domain model, and mapping it to a relational database. It's really hard to map inheritance to the SQL model (you end up with all sorts of hacky workarounds, like creating columns that aren't always used, using views, etc). Some ORMLs try to deal with this, but it always gets complicated quickly. Composition can be easily modeled through a foreign-key relationship between two tables, but inheritance is much harder.
While in short words I would agree with "Prefer composition over inheritance", very often for me it sounds like "prefer potatoes over coca-cola". There are places for inheritance and places for composition. You need to understand difference, then this question will disappear. What it really means for me is "if you are going to use inheritance - think again, chances are you need composition".
You should prefer potatoes over coca cola when you want to eat, and coca cola over potatoes when you want to drink.
Creating a subclass should mean more than just a convenient way to call superclass methods. You should use inheritance when subclass "is-a" super class both structurally and functionally, when it can be used as superclass and you are going to use that. If it is not the case - it is not inheritance, but something else. Composition is when your objects consists of another, or has some relationship to them.
So for me it looks like if someone does not know if he needs inheritance or composition, the real problem is that he does not know if he want to drink or to eat. Think about your problem domain more, understand it better.
Didn't find a satisfactory answer here, so I wrote a new one.
To understand why "prefer composition over inheritance", we need first get back the assumption omitted in this shortened idiom.
There are two benefits of inheritance: subtyping and subclassing
Subtyping means conforming to a type (interface) signature, i.e. a set of APIs, and one can override part of the signature to achieve subtyping polymorphism.
Subclassing means implicit reuse of method implementations.
With the two benefits comes two different purposes for doing inheritance: subtyping oriented and code reuse oriented.
If code reuse is the sole purpose, subclassing may give one more than what he needs, i.e. some public methods of the parent class don't make much sense for the child class. In this case, instead of favoring composition over inheritance, composition is demanded. This is also where the "is-a" vs. "has-a" notion comes from.
So only when subtyping is purposed, i.e. to use the new class later in a polymorphic manner, do we face the problem of choosing inheritance or composition. This is the assumption that gets omitted in the shortened idiom under discussion.
To subtype is to conform to a type signature, this means composition has always to expose no less amount of APIs of the type. Now the trade offs kick in:
Inheritance provides straightforward code reuse if not overridden, while composition has to re-code every API, even if it's just a simple job of delegation.
Inheritance provides straightforward open recursion via the internal polymorphic site this, i.e. invoking overriding method (or even type) in another member function, either public or private (though discouraged). Open recursion can be simulated via composition, but it requires extra effort and may not always viable(?). This answer to a duplicated question talks something similar.
Inheritance exposes protected members. This breaks encapsulation of the parent class, and if used by subclass, another dependency between the child and its parent is introduced.
Composition has the befit of inversion of control, and its dependency can be injected dynamically, as is shown in decorator pattern and proxy pattern.
Composition has the benefit of combinator-oriented programming, i.e. working in a way like the composite pattern.
Composition immediately follows programming to an interface.
Composition has the benefit of easy multiple inheritance.
With the above trade offs in mind, we hence prefer composition over inheritance. Yet for tightly related classes, i.e. when implicit code reuse really make benefits, or the magic power of open recursion is desired, inheritance shall be the choice.
Inheritance is pretty enticing especially coming from procedural-land and it often looks deceptively elegant. I mean all I need to do is add this one bit of functionality to some other class, right? Well, one of the problems is that inheritance is probably the worst form of coupling you can have
Your base class breaks encapsulation by exposing implementation details to subclasses in the form of protected members. This makes your system rigid and fragile. The more tragic flaw however is the new subclass brings with it all the baggage and opinion of the inheritance chain.
The article, Inheritance is Evil: The Epic Fail of the DataAnnotationsModelBinder, walks through an example of this in C#. It shows the use of inheritance when composition should have been used and how it could be refactored.
When can you use composition?
You can always use composition. In some cases, inheritance is also possible and may lead to a more powerful and/or intuitive API, but composition is always an option.
When can you use inheritance?
It is often said that if "a bar is a foo", then the class Bar can inherit the class Foo. Unfortunately, this test alone is not reliable, use the following instead:
a bar is a foo, AND
bars can do everything that foos can do.
The first test ensures that all getters of Foo make sense in Bar (= shared properties), while the second test makes sure that all setters of Foo make sense in Bar (= shared functionality).
Example: Dog/Animal
A dog is an animal AND dogs can do everything that animals can do (such as breathing, moving, etc.). Therefore, the class Dog can inherit the class Animal.
Counter-example: Circle/Ellipse
A circle is an ellipse BUT circles can't do everything that ellipses can do. For example, circles can't stretch, while ellipses can. Therefore, the class Circle cannot inherit the class Ellipse.
This is called the Circle-Ellipse problem, which isn't really a problem, but more an indication that "a bar is a foo" isn't a reliable test by itself. In particular, this example highlights that derived classes should extend the functionality of base classes, never restrict it. Otherwise, the base class couldn't be used polymorphically. Adding the test "bars can do everything that foos can do" ensures that polymorphic use is possible, and is equivalent to the Liskov Substitution Principle:
Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it
When should you use inheritance?
Even if you can use inheritance doesn't mean you should: using composition is always an option. Inheritance is a powerful tool allowing implicit code reuse and dynamic dispatch, but it does come with a few disadvantages, which is why composition is often preferred. The trade-offs between inheritance and composition aren't obvious, and in my opinion are best explained in lcn's answer.
As a rule of thumb, I tend to choose inheritance over composition when polymorphic use is expected to be very common, in which case the power of dynamic dispatch can lead to a much more readable and elegant API. For example, having a polymorphic class Widget in GUI frameworks, or a polymorphic class Node in XML libraries allows to have an API which is much more readable and intuitive to use than what you would have with a solution purely based on composition.
In Java or C#, an object cannot change its type once it has been instantiated.
So, if your object need to appear as a different object or behave differently depending on an object state or conditions, then use Composition: Refer to State and Strategy Design Patterns.
If the object need to be of the same type, then use Inheritance or implement interfaces.
Personally I learned to always prefer composition over inheritance. There is no programmatic problem you can solve with inheritance which you cannot solve with composition; though you may have to use Interfaces(Java) or Protocols(Obj-C) in some cases. Since C++ doesn't know any such thing, you'll have to use abstract base classes, which means you cannot get entirely rid of inheritance in C++.
Composition is often more logical, it provides better abstraction, better encapsulation, better code reuse (especially in very large projects) and is less likely to break anything at a distance just because you made an isolated change anywhere in your code. It also makes it easier to uphold the "Single Responsibility Principle", which is often summarized as "There should never be more than one reason for a class to change.", and it means that every class exists for a specific purpose and it should only have methods that are directly related to its purpose. Also having a very shallow inheritance tree makes it much easier to keep the overview even when your project starts to get really large. Many people think that inheritance represents our real world pretty well, but that isn't the truth. The real world uses much more composition than inheritance. Pretty much every real world object you can hold in your hand has been composed out of other, smaller real world objects.
There are downsides of composition, though. If you skip inheritance altogether and only focus on composition, you will notice that you often have to write a couple of extra code lines that weren't necessary if you had used inheritance. You are also sometimes forced to repeat yourself and this violates the DRY Principle (DRY = Don't Repeat Yourself). Also composition often requires delegation, and a method is just calling another method of another object with no other code surrounding this call. Such "double method calls" (which may easily extend to triple or quadruple method calls and even farther than that) have much worse performance than inheritance, where you simply inherit a method of your parent. Calling an inherited method may be equally fast as calling a non-inherited one, or it may be slightly slower, but is usually still faster than two consecutive method calls.
You may have noticed that most OO languages don't allow multiple inheritance. While there are a couple of cases where multiple inheritance can really buy you something, but those are rather exceptions than the rule. Whenever you run into a situation where you think "multiple inheritance would be a really cool feature to solve this problem", you are usually at a point where you should re-think inheritance altogether, since even it may require a couple of extra code lines, a solution based on composition will usually turn out to be much more elegant, flexible and future proof.
Inheritance is really a cool feature, but I'm afraid it has been overused the last couple of years. People treated inheritance as the one hammer that can nail it all, regardless if it was actually a nail, a screw, or maybe a something completely different.
My general rule of thumb: Before using inheritance, consider if composition makes more sense.
Reason: Subclassing usually means more complexity and connectedness, i.e. harder to change, maintain, and scale without making mistakes.
A much more complete and concrete answer from Tim Boudreau of Sun:
Common problems to the use of inheritance as I see it are:
Innocent acts can have unexpected results - The classic example of this is calls to overridable methods from the superclass
constructor, before the subclasses instance fields have been
initialized. In a perfect world, nobody would ever do that. This is
not a perfect world.
It offers perverse temptations for subclassers to make assumptions about order of method calls and such - such assumptions tend not to
be stable if the superclass may evolve over time. See also my toaster
and coffee pot analogy.
Classes get heavier - you don't necessarily know what work your superclass is doing in its constructor, or how much memory it's going
to use. So constructing some innocent would-be lightweight object can
be far more expensive than you think, and this may change over time if
the superclass evolves
It encourages an explosion of subclasses. Classloading costs time, more classes costs memory. This may be a non-issue until you're
dealing with an app on the scale of NetBeans, but there, we had real
issues with, for example, menus being slow because the first display
of a menu triggered massive class loading. We fixed this by moving to
more declarative syntax and other techniques, but that cost time to
fix as well.
It makes it harder to change things later - if you've made a class public, swapping the superclass is going to break subclasses -
it's a choice which, once you've made the code public, you're married
to. So if you're not altering the real functionality to your
superclass, you get much more freedom to change things later if you
use, rather than extend the thing you need. Take, for example,
subclassing JPanel - this is usually wrong; and if the subclass is
public somewhere, you never get a chance to revisit that decision. If
it's accessed as JComponent getThePanel() , you can still do it (hint:
expose models for the components within as your API).
Object hierarchies don't scale (or making them scale later is much harder than planning ahead) - this is the classic "too many layers"
problem. I'll go into this below, and how the AskTheOracle pattern can
solve it (though it may offend OOP purists).
...
My take on what to do, if you do allow for inheritance, which you may
take with a grain of salt is:
Expose no fields, ever, except constants
Methods shall be either abstract or final
Call no methods from the superclass constructor
...
all of this applies less to small projects than large ones, and less
to private classes than public ones
Inheritance is very powerful, but you can't force it (see: the circle-ellipse problem). If you really can't be completely sure of a true "is-a" subtype relationship, then it's best to go with composition.
Inheritance creates a strong relationship between a subclass and super class; subclass must be aware of super class'es implementation details. Creating the super class is much harder, when you have to think about how it can be extended. You have to document class invariants carefully, and state what other methods overridable methods use internally.
Inheritance is sometimes useful, if the hierarchy really represents a is-a-relationship. It relates to Open-Closed Principle, which states that classes should be closed for modification but open to extension. That way you can have polymorphism; to have a generic method that deals with super type and its methods, but via dynamic dispatch the method of subclass is invoked. This is flexible, and helps to create indirection, which is essential in software (to know less about implementation details).
Inheritance is easily overused, though, and creates additional complexity, with hard dependencies between classes. Also understanding what happens during execution of a program gets pretty hard due to layers and dynamic selection of method calls.
I would suggest using composing as the default. It is more modular, and gives the benefit of late binding (you can change the component dynamically). Also it's easier to test the things separately. And if you need to use a method from a class, you are not forced to be of certain form (Liskov Substitution Principle).
Suppose an aircraft has only two parts: an engine and wings.
Then there are two ways to design an aircraft class.
Class Aircraft extends Engine{
var wings;
}
Now your aircraft can start with having fixed wings
and change them to rotary wings on the fly. It's essentially
an engine with wings. But what if I wanted to change
the engine on the fly as well?
Either the base class Engine exposes a mutator to change its
properties, or I redesign Aircraft as:
Class Aircraft {
var wings;
var engine;
}
Now, I can replace my engine on the fly as well.
If you want the canonical, textbook answer people have been giving since the rise of OOP (which you see many people giving in these answers), then apply the following rule: "if you have an is-a relationship, use inheritance. If you have a has-a relationship, use composition".
This is the traditional advice, and if that satisfies you, you can stop reading here and go on your merry way. For everyone else...
is-a/has-a comparisons have problems
For example:
A square is-a rectangle, but if your rectangle class has setWidth()/setHeight() methods, then there's no reasonable way to make a Square inherit from Rectangle without breaking Liskov's substitution principle.
An is-a relationship can often be rephrased to sound like a has-a relationship. For example, an employee is-a person, but a person also has-an employment status of "employed".
is-a relationships can lead to nasty multiple inheritance hierarchies if you're not careful. After all, there's no rule in English that states that an object is exactly one thing.
People are quick to pass this "rule" around, but has anyone ever tried to back it up, or explain why it's a good heuristic to follow? Sure, it fits nicely into the idea that OOP is supposed to model the real world, but that's not in-and-of-itself a reason to adopt a principle.
See this StackOverflow question for more reading on this subject.
To know when to use inheritance vs composition, we first need to understand the pros and cons of each.
The problems with implementation inheritance
Other answers have done a wonderful job at explaining the issues with inheritance, so I'll try to not delve into too many details here. But, here's a brief list:
It can be difficult to follow a logic that weaves between base and sub-class methods.
Carelessly implementing one method in your class by calling another overridable method will cause you to leak implementation details and break encapsulation, as the end-user could override your method and detect when you internally call it. (See "Effective Java" item 18).
The fragile base problem, which simply states that your end-user's code will break if they happen to depend on the leakage of implementation details when you attempt to change them. To make matters worse, most OOP languages allow inheritance by default - API designers who aren't proactively preventing people from inheriting from their public classes need to be extra cautious whenever they refactor their base classes. Unfortunately, the fragile base problem is often misunderstood, causing many to not understand what it takes to maintain a class that anyone can inherit from.
The deadly diamond of death
The problems with composition
It can sometimes be a little verbose.
That's it. I'm serious. This is still a real issue and can sometimes create conflict with the DRY principle, but it's generally not that bad, at least compared to the myriad of pitfalls associated with inheritance.
When should inheritance be used?
Next time you're drawing out your fancy UML diagrams for a project (if you do that), and you're thinking about adding in some inheritance, please adhere to the following advice: don't.
At least, not yet.
Inheritance is sold as a tool to achieve polymorphism, but bundled with it is this powerful code-reuse system, that frankly, most code doesn't need. The problem is, as soon as you publicly expose your inheritance hierarchy, you're locked into this particular style of code-reuse, even if it's overkill to solve your particular problem.
To avoid this, my two cents would be to never expose your base classes publicly.
If you need polymorphism, use an interface.
If you need to allow people to customize the behavior of your class, provide explicit hook-in points via the strategy pattern, it's a more readable way to accomplish this, plus, it's easier to keep this sort of API stable as you're in full control over what behaviors they can and can not change.
If you're trying to follow the open-closed principle by using inheritance to avoid adding a much-needed update to a class, just don't. Update the class. Your codebase will be much cleaner if you actually take ownership of the code you're hired to maintain instead of trying to tack stuff onto the side of it. If you're scared about introducing bugs, then get the existing code under test.
If you need to reuse code, start out by trying to use composition or helper functions.
Finally, if you've decided that there's no other good option, and you must use inheritance to achieve the code-reuse that you need, then you can use it, but, follow these four P.A.I.L. rules of restricted inheritance to keep it sane.
Use inheritance as a private implementation detail. Don't expose your base class publicly, use interfaces for that. This lets you freely add or remove inheritance as you see fit without making a breaking change.
Keep your base class abstract. It makes it easier to divide out the logic that needs to be shared from the logic that doesn't.
Isolate your base and child classes. Don't let your subclass override base class methods (use the strategy pattern for that), and avoid having them expect properties/methods to exist on each other, use other forms of code-sharing to achieve that. Use appropriate language features to force all methods on the base class to be non-overridable ("final" in Java, or non-virtual in C#).
Inheritance is a last resort.
The Isolate rule in particular may sound a little rough to follow, but if you discipline yourself, you'll get some pretty nice benefits. In particular, it gives you the freedom to avoid all of the main nasty pitfalls associated with the inheritance that were mentioned above.
It's much easier to follow the code because it doesn't weave in and out of base/sub classes.
You can not accidentally leak when your methods are internally calling other overridable methods if you never make any of your methods overridable. In other words, you won't accidentally break encapsulation.
The fragile base class problem stems from the ability to depend on accidentally leaked implementation details. Since the base class is now isolated, it will be no more fragile than a class depending on another via composition.
The deadly diamond of death isn't an issue anymore, since there's simply no need to have multiple layers of inheritance. If you have the abstract base classes B and C, which both share a lot of functionality, just move that functionality out of B and C and into a new abstract base class, class D. Anyone who inherited from B should update to inherit from both B and D, and anyone who inherited from C should inherit from C and D. Since your base classes are all private implementation details, it shouldn't be too difficult to figure out who's inheriting from what, to make these changes.
Conclusion
My primary suggestion would be to use your brain on this matter. What's far more important than a list of dos and don'ts about when to use inheritance is an intuitive understanding of inheritance and its associated pros and cons, along with a good understanding of the other tools out there that can be used instead of inheritance (composition isn't the only alternative. For example, the strategy pattern is an amazing tool that's forgotten far too often). Perhaps when you have a good, solid understanding of all of these tools, you'll choose to use inheritance more often than I would recommend, and that's completely fine. At least, you're making an informed decision, and aren't just using inheritance because that's the only way you know how to do it.
Further reading:
An article I wrote on this subject, that dives even deeper and provides examples.
A webpage talking about three different jobs that inheritance does, and how those jobs can be done via other means in the Go language.
A list of reasons why it can be good to declare your class as non-inheritable (e.g. "final" in Java).
The "Effective Java" book by Joshua Bloch, item 18, which discusses composition over inheritance, and some of the dangers of inheritance.
You need to have a look at The Liskov Substitution Principle in Uncle Bob's SOLID principles of class design. :)
To address this question from a different perspective for newer programmers:
Inheritance is often taught early when we learn object-oriented programming, so it's seen as an easy solution to a common problem.
I have three classes that all need some common functionality. So if I
write a base class and have them all inherit from it, then they will
all have that functionality and I'll only need to maintain it in once
place.
It sounds great, but in practice it almost never, ever works, for one of several reasons:
We discover that there are some other functions that we want our classes to have. If the way that we add functionality to classes is through inheritance, we have to decide - do we add it to the existing base class, even though not every class that inherits from it needs that functionality? Do we create another base class? But what about classes that already inherit from the other base class?
We discover that for just one of the classes that inherits from our base class we want the base class to behave a little differently. So now we go back and tinker with our base class, maybe adding some virtual methods, or even worse, some code that says, "If I'm inherited type A, do this, but if I'm inherited type B, do that." That's bad for lots of reasons. One is that every time we change the base class, we're effectively changing every inherited class. So we're really changing class A, B, C, and D because we need a slightly different behavior in class A. As careful as we think we are, we might break one of those classes for reasons that have nothing to do with those classes.
We might know why we decided to make all of these classes inherit from each other, but it might not (probably won't) make sense to someone else who has to maintain our code. We might force them into a difficult choice - do I do something really ugly and messy to make the change I need (see the previous bullet point) or do I just rewrite a bunch of this.
In the end, we tie our code in some difficult knots and get no benefit whatsoever from it except that we get to say, "Cool, I learned about inheritance and now I used it." That's not meant to be condescending because we've all done it. But we all did it because no one told us not to.
As soon as someone explained "favor composition over inheritance" to me, I thought back over every time I tried to share functionality between classes using inheritance and realized that most of the time it didn't really work well.
The antidote is the Single Responsibility Principle. Think of it as a constraint. My class must do one thing. I must be able to give my class a name that somehow describes that one thing it does. (There are exceptions to everything, but absolute rules are sometimes better when we're learning.) It follows that I cannot write a base class called ObjectBaseThatContainsVariousFunctionsNeededByDifferentClasses. Whatever distinct functionality I need must be in its own class, and then other classes that need that functionality can depend on that class, not inherit from it.
At the risk of oversimplifying, that's composition - composing multiple classes to work together. And once we form that habit we find that it's much more flexible, maintainable, and testable than using inheritance.
When you want to "copy"/Expose the base class' API, you use inheritance. When you only want to "copy" functionality, use delegation.
One example of this: You want to create a Stack out of a List. Stack only has pop, push and peek. You shouldn't use inheritance given that you don't want push_back, push_front, removeAt, et al.-kind of functionality in a Stack.
These two ways can live together just fine and actually support each other.
Composition is just playing it modular: you create interface similar to the parent class, create new object and delegate calls to it. If these objects need not to know of each other, it's quite safe and easy to use composition. There are so many possibilites here.
However, if the parent class for some reason needs to access functions provided by the "child class" for inexperienced programmer it may look like it's a great place to use inheritance. The parent class can just call it's own abstract "foo()" which is overwritten by the subclass and then it can give the value to the abstract base.
It looks like a nice idea, but in many cases it's better just give the class an object which implements the foo() (or even set the value provided the foo() manually) than to inherit the new class from some base class which requires the function foo() to be specified.
Why?
Because inheritance is a poor way of moving information.
The composition has a real edge here: the relationship can be reversed: the "parent class" or "abstract worker" can aggregate any specific "child" objects implementing certain interface + any child can be set inside any other type of parent, which accepts it's type. And there can be any number of objects, for example MergeSort or QuickSort could sort any list of objects implementing an abstract Compare -interface. Or to put it another way: any group of objects which implement "foo()" and other group of objects which can make use of objects having "foo()" can play together.
I can think of three real reasons for using inheritance:
You have many classes with same interface and you want to save time writing them
You have to use same Base Class for each object
You need to modify the private variables, which can not be public in any case
If these are true, then it is probably necessary to use inheritance.
There is nothing bad in using reason 1, it is very good thing to have a solid interface on your objects. This can be done using composition or with inheritance, no problem - if this interface is simple and does not change. Usually inheritance is quite effective here.
If the reason is number 2 it gets a bit tricky. Do you really only need to use the same base class? In general, just using the same base class is not good enough, but it may be a requirement of your framework, a design consideration which can not be avoided.
However, if you want to use the private variables, the case 3, then you may be in trouble. If you consider global variables unsafe, then you should consider using inheritance to get access to private variables also unsafe. Mind you, global variables are not all THAT bad - databases are essentially big set of global variables. But if you can handle it, then it's quite fine.
Aside from is a/has a considerations, one must also consider the "depth" of inheritance your object has to go through. Anything beyond five or six levels of inheritance deep might cause unexpected casting and boxing/unboxing problems, and in those cases it might be wise to compose your object instead.
When you have an is-a relation between two classes (example dog is a canine), you go for inheritance.
On the other hand when you have has-a or some adjective relationship between two classes (student has courses) or (teacher studies courses), you chose composition.
A simple way to make sense of this would be that inheritance should be used when you need an object of your class to have the same interface as its parent class, so that it can thereby be treated as an object of the parent class (upcasting). Moreover, function calls on a derived class object would remain the same everywhere in code, but the specific method to call would be determined at runtime (i.e. the low-level implementation differs, the high-level interface remains the same).
Composition should be used when you do not need the new class to have the same interface, i.e. you wish to conceal certain aspects of the class' implementation which the user of that class need not know about. So composition is more in the way of supporting encapsulation (i.e. concealing the implementation) while inheritance is meant to support abstraction (i.e. providing a simplified representation of something, in this case the same interface for a range of types with different internals).
Subtyping is appropriate and more powerful where the invariants can be enumerated, else use function composition for extensibility.
I agree with #Pavel, when he says, there are places for composition and there are places for inheritance.
I think inheritance should be used if your answer is an affirmative to any of these questions.
Is your class part of a structure that benefits from polymorphism ? For example, if you had a Shape class, which declares a method called draw(), then we clearly need Circle and Square classes to be subclasses of Shape, so that their client classes would depend on Shape and not on specific subclasses.
Does your class need to re-use any high level interactions defined in another class ? The template method design pattern would be impossible to implement without inheritance. I believe all extensible frameworks use this pattern.
However, if your intention is purely that of code re-use, then composition most likely is a better design choice.
Inheritance is a very powerfull machanism for code reuse. But needs to be used properly. I would say that inheritance is used correctly if the subclass is also a subtype of the parent class. As mentioned above, the Liskov Substitution Principle is the key point here.
Subclass is not the same as subtype. You might create subclasses that are not subtypes (and this is when you should use composition). To understand what a subtype is, lets start giving an explanation of what a type is.
When we say that the number 5 is of type integer, we are stating that 5 belongs to a set of possible values (as an example, see the possible values for the Java primitive types). We are also stating that there is a valid set of methods I can perform on the value like addition and subtraction. And finally we are stating that there are a set of properties that are always satisfied, for example, if I add the values 3 and 5, I will get 8 as a result.
To give another example, think about the abstract data types, Set of integers and List of integers, the values they can hold are restricted to integers. They both support a set of methods, like add(newValue) and size(). And they both have different properties (class invariant), Sets does not allow duplicates while List does allow duplicates (of course there are other properties that they both satisfy).
Subtype is also a type, which has a relation to another type, called parent type (or supertype). The subtype must satisfy the features (values, methods and properties) of the parent type. The relation means that in any context where the supertype is expected, it can be substitutable by a subtype, without affecting the behaviour of the execution. Let’s go to see some code to exemplify what I’m saying. Suppose I write a List of integers (in some sort of pseudo language):
class List {
data = new Array();
Integer size() {
return data.length;
}
add(Integer anInteger) {
data[data.length] = anInteger;
}
}
Then, I write the Set of integers as a subclass of the List of integers:
class Set, inheriting from: List {
add(Integer anInteger) {
if (data.notContains(anInteger)) {
super.add(anInteger);
}
}
}
Our Set of integers class is a subclass of List of Integers, but is not a subtype, due to it is not satisfying all the features of the List class. The values, and the signature of the methods are satisfied but the properties are not. The behaviour of the add(Integer) method has been clearly changed, not preserving the properties of the parent type. Think from the point of view of the client of your classes. They might receive a Set of integers where a List of integers is expected. The client might want to add a value and get that value added to the List even if that value already exist in the List. But her wont get that behaviour if the value exists. A big suprise for her!
This is a classic example of an improper use of inheritance. Use composition in this case.
(a fragment from: use inheritance properly).
Even though Composition is preferred, I would like to highlight pros of Inheritance and cons of Composition.
Pros of Inheritance:
It establishes a logical "IS A" relation. If Car and Truck are two types of Vehicle ( base class), child class IS A base class.
i.e.
Car is a Vehicle
Truck is a Vehicle
With inheritance, you can define/modify/extend a capability
Base class provides no implementation and sub-class has to override complete method (abstract) => You can implement a contract
Base class provides default implementation and sub-class can change the behaviour => You can re-define contract
Sub-class adds extension to base class implementation by calling super.methodName() as first statement => You can extend a contract
Base class defines structure of the algorithm and sub-class will override a part of algorithm => You can implement Template_method without change in base class skeleton
Cons of Composition:
In inheritance, subclass can directly invoke base class method even though it's not implementing base class method because of IS A relation. If you use composition, you have to add methods in container class to expose contained class API
e.g. If Car contains Vehicle and if you have to get price of the Car, which has been defined in Vehicle, your code will be like this
class Vehicle{
protected double getPrice(){
// return price
}
}
class Car{
Vehicle vehicle;
protected double getPrice(){
return vehicle.getPrice();
}
}
A rule of thumb I have heard is inheritance should be used when its a "is-a" relationship and composition when its a "has-a". Even with that I feel that you should always lean towards composition because it eliminates a lot of complexity.
As many people told, I will first start with the check - whether there exists an "is-a" relationship. If it exists I usually check the following:
Whether the base class can be instantiated. That is, whether the base class can be non-abstract. If it can be non-abstract I usually prefer composition
E.g 1. Accountant is an Employee. But I will not use inheritance because a Employee object can be instantiated.
E.g 2. Book is a SellingItem. A SellingItem cannot be instantiated - it is abstract concept. Hence I will use inheritacne. The SellingItem is an abstract base class (or interface in C#)
What do you think about this approach?
Also, I support #anon answer in Why use inheritance at all?
The main reason for using inheritance is not as a form of composition - it is so you can get polymorphic behaviour. If you don't need polymorphism, you probably should not be using inheritance.
#MatthieuM. says in https://softwareengineering.stackexchange.com/questions/12439/code-smell-inheritance-abuse/12448#comment303759_12448
The issue with inheritance is that it can be used for two orthogonal purposes:
interface (for polymorphism)
implementation (for code reuse)
REFERENCE
Which class design is better?
Inheritance vs. Aggregation
Composition v/s Inheritance is a wide subject. There is no real answer for what is better as I think it all depends on the design of the system.
Generally type of relationship between object provide better information to choose one of them.
If relation type is "IS-A" relation then Inheritance is better approach.
otherwise relation type is "HAS-A" relation then composition will better approach.
Its totally depend on entity relationship.

Struggling to decide if a single-method interface is really a good idea in my case here?

So I currently have an interface, Rentable, intended to be implemented by any object which needs to be, well, rentable, that has three methods:
boolean isRented();
void rent();
void terminateRental();
Thing is, in classes that implement this interface, the ability to rent and terminate the rental of the implementing object should really be package-private, though obviously I didn't realise this when first writing up my class structure.
A separate rental manager class is providing the public methods to rent a Rentable and associate it with another object representing the individual renting it, and this class is the only thing that should really be calling the rent and terminateRental methods in the Rentable object itself. As obviously if other classes can publicly manipulate the rented status of the object without disassociating it from the person renting it, that's a problem.
So really these last two methods from the interface should be package-private, so obviously they need to come out of the interface, but then is having the interface:
public interface Rentable {
boolean isRented();
}
... really a good idea or good practice? I've looked up single-method interfaces and when they're a good idea or not but can't find much relating to this kind of situation. It seems slightly wrong to me, although I suppose the fact that it requires an object have a rented status implies methods to change it need to be written, and it could be good for me to support other objects becoming Rentable in the future (currently it's just Cars, but potentially other types of vehicles or services could be rented). But I'm just not sure how good practice this is, or if there's some kind of alternative in this situation I'm not seeing?
There is nothing inherently wrong with single-method interfaces (and the standard library contains some, however relevant that may or may not be). If the only thing you need implementations to guarantee to their clients is the ability to communicate whether they are rented, then the interface you propose is fine.
Note, too, that there is more to an interface than just its methods: interfaces are bona fide types. If you are not using this interface that way -- as the declared type or type parameter of variables, method parameters, and/or return types -- then you really are not getting much out of it.

Explaining Interfaces to Students [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
For a few years I was a teaching assistant for an introduction to programming module - Java for first year undergraduates.
Mostly it went well and we managed to get object-oriented programming across to the students quite well, but one thing that students rarely saw the point of was interfaces.
Pretty much any explanation we gave either came across as too contrived to be useful for learning, or too far removed from their position as beginners. The reaction we tended to get was "I... see," translated as "I don't understand and they don't sound useful".
Anyone here have a way of successfully teaching students about interfaces? I'm not a teaching assistant any more, but it's always nagged at me.
If you are trying to explain it to beginners I would stick with the idea that interfaces can promote code reuse and modularity within the code:
For example lets say we are going to paint some objects:
public class Painter {
private List<Paintable> paintableObjects;
public Painter(){
paintableObjects = new ArrayList<Paintable>();
}
public void paintAllObjects(){
for(Paintable paintable : paintableObjects){
paintable.paint();
}
}
}
public interface Paintable {
public void paint();
}
Now you could explain to the students that without Paintable interface the Painter object would need to have methods to paint certain types of objects, like a method called paintFences() and paintRocks() and we would need to have a new Collection for each type of objects we want the painter to be able to paint.
But thankfully we have interfaces which make painting objects a breeze and how objects are painted is left entirely up to classes that implement the Paintable interface.
EDIT
Another benefit that I forgot to mention is that if you ever need to add new object to paint to your code base, all you need to do is create a new class that implements Paintable and the Painter class never has to change. In this sense the Painter class is never dependent upon the objects it is going to paint, it only needs to be able to paint them.
EDIT 2
James Raybould reminded me of a key use of interfaces I forgot to mention: Having an interface between your components, like the Paintable objects and Painter objects, allows you to more easily develop with other people. One developer can work on the Painter objects and another can work on the Paintable objects and all they have to do to function properly together is define a common interface beforehand that they will both use. I know when I've worked on projects with other people in college level projects its really helpful when you are trying to have everyone work on different parts of the project and still have all components come together nicely in the end.
In explaining interfaces and object oriented concepts in general to non-programmers, I always use the home entertainment system analogy.
The DVD player, TV, Cable Box, Remote Control are all objects that encapsulate complicated and sophisticated functionality. However, they have interfaces to each other and to the Humans that operate them that largely hide the lion share of that complexity.
The video in jack of a TV is an interface that is implemented by the DVD player and the cable box and a number of other types of devices.
I suspect it would be possible and perhaps an educational exercise for a student to describe their own home entertainment system entirely using Java code.
"Where classes ARE something, typically interfaces DO something. So I might have a car, but I would never go "carring" but I might go driving... so my Car might implement "drivable" interface."
EDIT:
Mark brings up a good point. Interfaces don't do anything at all, but instead define what behaviors happen. And, he also brings up a good point about not wanting to confuse the audience. Not that it's okay to confuse seasoned developers, but it's definitely not a good idea to confuse a brand new student. In light of this, I'm revising my one-liner into a many-liner.
"Where classes define existence, interfaces define behavior. Classes define what something is, while interfaces define what something does. So I might have a car, and it has things like an Engine, how much gas it has, what it's historic MPG is, and the like, but I would never go "carring". I might, on the other hand, go Driving... can my Car drive? It can if I give it a Drive method. I can also have "Driveable" interface with a drive method, and leave it up to the car to determine what driving really means. Now, if I only have cars it's not a big deal to have an interface. But what about trucks? If they both are Drivable, I can simply have a List<Drivable for both of them. Of course, the observant student says "Why can't Car and Truck both simply extend Vehicle, with an abstract Drive method?" Which, actually is a very valid notion. But, what about the Space Shuttle? Very few of the components between Car and Truck apply to the Space Shuttle, so it doesn't seem well suited to extend the Vehicle class. Or what about future cars? We have no idea what they might be like, they might not have chassises, they might just be bubbles of energy that move us around, but we might still call their behavior drive()."
breathes
Now that paragraph/essay is a little verbose, but I could see, with some slides or a chalkboard, being effective for first year students to get their head around (assuming they understand abstract classes first anyway).
Well I just explained interfaces to a work partner, she was learning java from progress and she really did not get all the OOP stuff at the beginning so I just explained everything from a non-software engineering point of view, my explanation for interfaces where something like this:
Suppose you want to hire a plumber to fix some things on your house, you don't know (and you don't care much) who you may end up hiring but you know what the plumber must be able to do. So, you define a set of tasks that anyone that claims to be a plumber must know how to do. Of course everybody might have its own way of carrying out each task, but in the end, the person you are hiring is a plumber because they know how to do each task. So, if you were to write this in java, the first thing to do would be to define an interface plumber like this:
public interface Plumber
{ //silly code here }
OK then, let's say that I know how to do each task you are requesting for and so I'm fully compliant with your requirements and so according to you I'm a plumber. So, today I decide to be your plumber and you decide to hire me (yay!), based on the last example, you can say that I'm a person that knows how to develop software and plumbing in a specific way, if I were to write code for me as a class I could write something like this:
public class Rick extends Person implements SoftwareDeveloper, Plumber
and later you could fix things in your house using me as your plumber:
Plumber thePlumber = rick;
thePlumber.fixLeak(myHouse.bathroom.leak) // =(
from this point on, the remaining OOP concepts were easy to explain.
Well, recently, I happened to explain this to someone close. The way I explained the question "why Interfaces?", is by taking example of of the USB Port and the USB drives.
The USB port can be considered as a specification, and any USB drive can fit into it, provided they implement the specification. So in this case, the port becomes the Interface and the numerous types of USB sticks available, become the class.
Carrying this example ahead, if I were to supply someone an USB drive (class), I would not need to tell them (the calling method) as to what am I passing across. Had the calling method taken a USB drive (class type) as a reference, I would not have been able to pass any but only the USB drive that the port is meant for.
To sum it up, Intefaces, help the caller be comptabile with the calling method (in a use-case when the calling method expects an instance of a particular type), no matter what instance you pass across, the caller as well as the callee are sure that it (instance) would fit into the Interface reference (the USB port for analogy).
Class, we spent the last few sessions implementing quicksort. It was difficult to sort that list of Persons by name. What would you now do, if you had to sort this list by grade? And what would you do if you had to sort a list of dinousaurs by age? The only way you know so far is to copy the code of the quicksort, and change the comparison and the types it operates on. That would work - until you find that elusive bug that always plagued your quicksort, and had to fix it in several dozen copies of that quicksort scattered all over the place.
Today, we are going to learn a better way.
We can write a quicksort without defining the order we want to sort the list into, and define that order (and only that order) separately when we invoke that quicksort.
[ insert explanation of the mechanics of interfaces and polymorphism, using the Comparator interface as example, here ]
Now, there is only a single copy of quicksort, and bugs only have to be fixed once. Also, people can use quicksort without understanding it (or if they have understood it, without thinking about its mechanics whenever you want to sort something). Also, the people writing the quicksort did not need to know the order you need your list sorted. So the interface isolated the two groups of programmers, allowing them to develop their parts of the software in isolation. This is why, in many programming languages, you will find well implemented and tested sort methods in the api, even though the programmers of these methods could not know all the types of objects and orders people want to sort into later.
I usually use "contract" but "promises solemnly to provide" might also help understanding.
I recommend the first chapter of Head First Design Patterns for this. The Duck simulation explains the problem with using inheritance, and the rest of the chapter goes on explaining how to do it.
This explains best : (referenced from this tutorial)
There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.
For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile—stop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.
The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group's software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.
More Link: http://download-llnw.oracle.com/javase/tutorial/java/concepts/interface.html
Understanding interfaces is not very different to understanding polymorphism and IS-A relationships. All classes implementing the same interface can be manipulated uniformly by the program as the "base" type because of the relationship established by implementing an interface or inheriting a base class.
The choice between an interface and a base class is a design decision. I'd keep this simple.
Define a class when your implementation can assume the complete or partial behavior of a class.
Make that class abstract to indicate the base class is not a complete implementation and cannot be used as is.
Provide an interface instead of a base class if it does not make sense to provide a partial implementation.
The benefits of interfaces and inheritance are pretty much the same. An interface is simply a more abstract definition of a type than a base class is.
Update
Here's a simple program you could use to demonstrate how similar inheritance and interfaces are. Modify the program to make Base an interface instead of a class. In ClassA, replace "extends" for "implements". The program's result will be the same.
The purpose of ClassB is to illustrate further illustrate the importance of the relationship between a class and its interface/base class. An instance of ClassB may not be passed to processBase in spite of its similarities with Base, unless we establish an explicit relationship.
abstract class Base {
public void behavior() {};
};
class ClassA extends Base {
public void behavior() {
System.out.println("ClassA implementation of Base behavior");
}
};
class ClassB {
public void behavior() {
System.out.println("ClassB's version of behavior");
}
}
public class InterfaceExample {
public void processBase (Base i) {
i.behavior();
}
public static void main (String args[]) {
InterfaceExample example = new InterfaceExample();
example.processBase(new ClassA());
}
}
Interface Oriented Design describes this better than I ever could http://pragprog.com/titles/kpiod/interface-oriented-design. The author uses some excellent examples of interfaces versus inheritance for things like the taxonomy of the animal kingdom. It has some of the best arguments against excessive inheritance and judicious use of interfaces I have read to date.
A bunch of websites with incompatible ways of bringing them up:
Listing of Facebook.java:
public class Facebook {
public void showFacebook() {
// ...
}
}
Listing of YouTube.java:
public class YouTube {
public void showYouTube() {
// ...
}
}
Listing of StackOverflow.java:
public class StackOverflow {
public void showStackOverflow() {
// ...
}
}
A client manually handling the different methods the websites use to bring
themselves up:
Listing of ClientWithoutInterface.java:
public class ClientWithoutInterface {
public static void main(String... args) {
String websiteRequested = args[0];
if ("facebook".equals(websiteRequested)) {
new Facebook().showFacebook();
} else if ("youtube".equals(websiteRequested)) {
new YouTube().showYouTube();
} else if ("stackoverflow".equals(websiteRequested)) {
new StackOverflow().showStackOverflow();
}
}
}
Introduce a Website interface to make the client's job easier:
Listing of Website.java:
public interface Website {
void showWebsite();
}
Listing of Facebook.java:
public class Facebook implements Website {
public void showWebsite() {
// ...
}
}
Listing of YouTube.java:
public class YouTube implements Website {
public void showWebsite() {
// ...
}
}
Listing of StackOverflow.java:
public class StackOverflow implements Website {
public void showWebsite() {
// ...
}
}
Listing of ClientWithInterface.java:
public class ClientWithInterface {
public static void main(String... args) {
String websiteRequested = args[0];
Website website;
if ("facebook".equals(websiteRequested)) {
website = new Facebook();
} else if ("youtube".equals(websiteRequested)) {
website = new YouTube();
} else if ("stackoverflow".equals(websiteRequested)) {
website = new StackOverflow();
}
website.showWebsite();
}
}
Whoop-de-doo, more code for nothing? Actually we can go a little further and
have the client rope a couple of friends into helping it find and render a
requested website:
Listing of ClientWithALittleHelpFromFriends.java:
public class ClientWithALittleHelpFromFriends {
public static void main(String... args) {
WebsiteFinder finder = new WebsiteFinder();
WebsiteRenderer renderer = new WebsiteRenderer();
renderer.render(finder.findWebsite(args[0]));
}
}
Listing of WebsiteFinder.java:
public class WebsiteFinder {
public Website findWebsite(String websiteRequested) {
if ("facebook".equals(websiteRequested)) {
return new Facebook();
} else if ("youtube".equals(websiteRequested)) {
return new YouTube();
} else if ("stackoverflow".equals(websiteRequested)) {
return new StackOverflow();
}
}
}
Listing of WebsiteRenderer.java:
public class WebsiteRenderer {
public void render(Website website) {
website.showWebsite();
}
}
Looking back at ClientWithoutInterface, it is totally coupled to both specific lookup and rendering based. It would be very difficult to manage when you get to hundreds or thousands of sites. With the Website interface in place the WebsiteFinder could easily be converted to be backed on a Map, a database or even a web based lookup to satisfy increasing scale.
Interfaces make it possible to separate a role from the component that achieves it. They make it possible to swap in alternative solutions to the same problem based on pretty much anything:
Current load on machine
Size of the data set (sorting algorithms can be picked)
User requesting the action being performed
I was typing this as a comment to Harima555s answer, but it expanded. I wondered if it makes more sense to start at the other end - give them a feel for how interfaces are useful, before going into how you write one.
Presuming they have a good grasp of inheritance, polymorphism and abstract classes. I would probably start with a recap on abstract classes, by asking one of the students to explain them.
Next, introduce an example of classes with interfaces to get over the concept of roles / contracts. To simplify things, start with a single superclass.
public class Rick extends Person implements SoftwareDeveloper, Plumber
public class Zoe extends Person implements SoftwareDeveloper, Chef
public class Paul extends Person implements Plumber, Chef
public class Lisa extends Person implements Plumber
Don't explain it too much, but try and get the student to work through what the syntax might mean - perhaps showing some code that references a Plumber or SoftwareDeveloper.
Ask them how they would achieve the same thing using inheritance from Person. They should get stuck quite quickly, or come up with multiple inheritance. To avoid discussing the diamond problem until later, say there are no overlapping methods in the roles.
Next I'd try to get over the idea that the same interface can be used on different types of Class.
public class Plane extends Vehicle implements Fly, PassengerTransport, Serviceable
public class Train extends Vehicle implements PassengerTransport, Serviceable
public class Bird extends Animal implements Fly
Again, try to get them to consider how they could implement the same thing using a common superclass and overrides.
Then illustrate how you would write polymorphic code using the interface rather than class - say a TravelAgent who sells tickets for a PassengerTransport. Dwell on the strength of this - that you can write polymorphic code that works on Classes from different hierarchies.
At this point, they should probably be under the illusion that an interface is a pretty much like being able to add another superclass to a class, and will have grasped the advantages of multiple inheritance.
So now we have to explain why that complicates things, and interfaces have no default implementation, via understanding the diamond problem.
Go back to the first example, get them to work through what happens if SoftwareDeveloper and Plumber both have a 'MakeDrink' method (one makes Cola, the other makes Coffee) and we execute MakeDrink on Rick.
Try and nudge someone towards considering the idea that if MakeDrink is kept abstract in both 'superclasses' the problem goes away. At this point, having got the conceptual side, we should be ready to cover the syntax for defining an interface.
(I did consider introducing the second reason - the difficulty of writing generic code that could be applied to different class hierarchies, but found that you end up with 'well why can't you inherit an altitude attribute from the interface' or discussing generic programming too early).
I think by now we should have covered the concepts via the mickey mouse examples - and you could then go back through explaining the correct technical terminology, and use real-world examples from the Java API.
I wouldn't want to confuse people while they are trying to learn Java/Interfaces, but once they've got it, it may be worth pointing out that other OO languages take different approaches to the same problem, from multiple inheritance to duck-typing - and if they are interested they should research them.
Do you teach JDBC as well? Take it as an example. It's an excellent real world example of how powerful interfaces are. In JDBC you're writing code against an API which exist of almost only interfaces. The JDBC driver is the concrete implementation. You can easily reuse the JDBC code on many DB's without rewriting the code. You just have to switch the JDBC driver implementation JAR file and driver class name to get it to work on another DB.
At least, using interfaces offers you the possibility to change from the concrete implementation (the code logic which is responsible for the behaviour) at some way/point without rewriting the whole code. Try to use real world examples when explaining things. It would make more sense.
Well, I found lately a very useful method of using interface.
We have many objects...
public class Settings { String[] keys; int values; }
public class Car { Engine engine; int value; }
public class Surface { int power; int elseInt; }
// and maaany more (dozens...)
Now, someone is creating (i.e.) table and want to show some of objects from the list of all objects, but to show objects in the list he must write method that returns String[].
String[] toArrayString()
So he just implements this method in all classes that he need to in table
public class Settings { String[] keys; int values; public String[] toArrayString {...} }
public class Car { Engine engine; int value; } // THIS NOT
public class Surface { int power; int elseInt; public String[] toArrayString {...} }
// and maaany more (dozens...)
Now, when he creates table he is writing smth like this
public void createTable() {
for(Object obj : allObjects) {
if(obj instanceof Settings) {
Settings settings = (Settings)obj;
table.add(settings.toArrayString());
}
if(obj instanceof Surface) {
// cast...
}
// etc multiple times...
}
}
With interface this code can be much shorter and easier to read and maintain:
public interface ISimpleInterface { String[] toArrayString; }
public class Settings implements ISimpleInterface { String[] keys; int values; public String[] toArrayString {...} }
public class Car { Engine engine; int value; } // THIS NOT
public class Surface implements ISimpleInterface { int power; int elseInt; public String[] toArrayString {...} }
public void createTable() {
for(Object obj : allObjects) {
if(obj instanceof ISimpleInterface) {
ISimpleInterface simple = (ISimpleInterface)obj;
table.add(simple.toArrayString());
}
}
}
Moreover, we can implement multiple interfaces in a very clean and effective way without any derivation (derivation is sometimes impossible and not only in case, when class is using some kind of other derivation already).
Interfaces provide a look at what a class needs to do for instance you can have an Animal interface and lets say that has a method called speak(), well each animal can speak but they all do it differently but this allows you to cast anything that implements animal to animal so you can have a List of animals and make them all speak but use their own implementation. Interfaces are simply wrappers for these kinds of things.
In this previous question there are some good scenarios that explain the whys behind the use of interfaces.
Stack Overflow Question
The real value of interfaces comes with being able to override components in 3rd party APIs or frameworks. I would construct an assignment where the students need to override functionality in a pre-built library that they cannot change (and do not have the source for).
To be more concrete, let's say you have a "framework" that generates an HTML page implemented as a Page class. And page.render(stream) generates the html. Let's say that Page takes an instance of the sealed ButtonTemplate class. The ButtonTemplate object has its own render method so that in page.render(stream) buttonTemplate.render(label,stream) gets called anywhere there is a button and it produces the html for a submit button. As an example to the students, let's say that we want to replace those submit buttons with links.
I wouldn't give them much direction other than describing the final output. They will have to pound their heads trying various solutions. "Should we try to parse out the button tags and replace with anchor tags? Can we subclass ButtonTemplate to do what we want? Oh, wait. It's sealed! What were they thinking when they sealed this class!?!" Then after that assignment show a second framework with the ILabeledTemplate interface with the render(label,stream) method.
In addition to the other answers, you could try explaining it from a different perspective. The students I'm sure already know about inheritance because it is jammed down the throats of every Java student from probably lecture one. Have they heard about multiple inheritance? Method resolution was seen as a design issue in C++ (and also in Perl and other multiple-inheritance languages) because conceptually it's ambiguous as to exactly what should happen when a method is called in a subclass that is defined in two of its base classes. Are both executed? Which one goes first? Can one be referenced specifically? See also the diamond problem. It's my understanding that this confusion was resolved simply by introducing interfaces, which have no implementation, so there's no ambiguity as to which implementation to use during method resolution.
If a class needed to handle exactly one piece of abstract functionality, and didn't need to inherit any other class, one could use an abstract class to expose the functionality and then derive the real class from that. Notice the two items in italics, however. Interfaces make it possible for a class to behave as several independent types of abstract things, even if the class is derived from another class that does not behave as those types of things. Thus, interfaces satisfy one of the main usage cases for multiple inheritance, without the ickiness that goes along with multiple inheritance.
A simple real-world example of a very practical interface: iEnumerable. If a class holds some arbitrary number of some type of item, is is very useful for another class to act upon all of those item without having to worry about the particulars of the object that holds them. If "enumerableThing" were an abstract class, it would be impossible for an object of any class which derived from something that wasn't an "enumerableThing" to be passed to code that expected an enumerableThing. Since any class, including derived classes, can implement enumerableThing without regard for whether the base classes do so, it's possible to add enumeration ability to any class.
A long time ago, I read a book (can't remember the name of it though) and it had a pretty good analogy for interfaces. If you (or your students) ever went to a Cold Stone Creamery ice cream store, this will sound kind of familiar. Cold Stone has ice cream and with the ice cream you can add several different things to the ice cream (called mix-ins at Cold Stone). These mix-ins would be analogous to interfaces. Your class (or ice cream) can have as many interfaces (or mix-ins) as you want. Adding an interface (or mix-in) will add the contents (or flavor) of that interface (or mix-in) to your class (or ice cream). Hope this helps!
Contracts are first things that are taught about interfaces but they are built in the language to provide the skills of multiple inheritance and avoid the complexity of multiple inheritance.. So you can teach them that interfaces add runtime behaviour to programs, or you can tell the students that interfaces can be used to change runtime behaviour of objects..
First, the students must grasp the concept of abstractions.
When you (you == the students) see a teacher, you can describe him as a teacher...
You can also describe him as an employe (of the school).
And you can describe him as a person.
You will be right the three times. Thoses are "titles" you can give him.
He is a teacher, a computer science teacher, in the same way a math teacher is a teacher.
They are on the same level of abstraction.
Now a teacher is an employee, in the same way a janitor is an employee.
They are on the same level of abstraction.
An employe is a person, in the same way an unemployed person is a person.
They are on the same level of abstraction.
(Draw the whole thing on the board in a UML kinda way).
And that's the architecture that will describe (roughly) the position of a science teacher in society.
Now the levels of abstraction define what a common group of objects have in common : All the teachers teach to their students and create impossible exam questions to make sure they fail. All the school's employes work for the school.
In programming, an interface is a level of abstraction. It describes the actions that a group of objects can accomplish.
Each object has a unique way of doing the action, but the type of action is the same.
Take a few music instruments for example : A piano, a guitar and a flute.
What do they have in common ? A musician can play them.
You can't ask a musician to blow in the 3 instruments but you can ask him to play them.
The architecture of the whole concept will be the following:
The Interface (what they have in common) is Instrument. Because they're all instruments : it's an abstraction they all have in common.
What can they do in common ? Play. So you define an abstract method called Play.
Now you can't define how the "Instrument" will play because it depends on the type of instrument.
Flute is a type of Instrument. So the class Flute implements Instrument.
Now you must define what the musician will do when he plays that type of instrument.
So you define the play method. This definition will override the definition of the Instrument.
Do the same with the 2 others instruments.
Now if you have a list of instruments but don't know what type they are, you can still "ask" them to play.
Each flute will be blown.
Each guitar will be scratched.
Each pianio will be ... huh... pianoted ? whatever !
But each object will know what to do to execute the action "Play". You don't know what kind of instrument they are, but since you know they are instruments, you ask them to play and they know how to do that.
You may also want to compare and contrast interfaces in Java with C++ (where you end up using multiple inheritance and/or "friend" classes).
(At least, to me, that showed me how much simpler/easier interfaces were in Java :-)
I would tell them "Interfaces define what behaviors are provided" and "Implementations provide those behaviors". A piece of code that uses an interface doesn't need the details of how things are happening, it only needs to know what things can happen.
A good example is the DAO pattern. It defines behavior like "save", "load", "delete". You could have an implementation that works with a DB, and an implementation that goes to the file system.
I think a lot of the other answers so far are too complicated for students who don't get it right away...
I think in general, hands-on learning always helps reinforce concepts after lectures and examples. So in the same vein as meriton suggests, I would present two versions of the same program. (quicksort is a good example)
Have the students modify each program several times, unveil subtle bugs in the program for them to fix. Your students will soon find, I think, that interfaces provide many advantages when designing a program when they're the ones who have to modify it later!
I always think of it as a mean to (verbally) communicate as little as possible because that (good communication) is the most difficult thing in software engineering. Same for Web Services and SOA. If you give somebody an interface and say "Please provide me this service." it is a very convenient way because you don't have to explain a lot, and the compiler will check if they did a proper job, instead of you! (I mean, not really but at least it'll ensure the methods are there).

Is it possible to unimplement an interface in derived class in Java?

Let's have the following class hierarchy:
public class ParentClass implements SomeInterface {
}
public class ChildClass extends ParentClass {
}
Then let's have these two instances:
ParentClass parent;
ChildClass child;
Then we have the following TRUE statements
(parent instanceof SomeInterface) == true
(child instanceof SomeInterface) == true
Is it possible to unimplement the SomeInterface in the ChildClass, so when we check with the instanceof operator it returns false?
If not possible, is there a workaround?
No it is not possible, and your intent to do so is a good hint that something is flawed in your class hierarchy.
Workaround: change the class hierarchy, eg. like this:
interface SomeInterface {}
abstract class AbstractParentClass {}
class ParentClass extends AbstractParentClass implements SomeInterface {}
class ChildClass extends AbstractParentClass {}
Maybe composition instead of inheritance is what you want, i.e. have a "base class" object as a member and just implement the interfaces you need, forwarding any methods needed to the member.
I agree with other answers that it is not possible in Java.
The other answers further suggest it shows a flaw in your design.
While I agree with them, it is only fair to point out that some prominent OO experts (particularly Bertrand Meyer) disagree with us, and believe such a design should be allowed.
Other OO inheritance models (notably, Meyer's Eiffel programming language) do support the "Change of Availability or Type" (CAT) feature that you are looking for.
It's not possible and doing so would violate the implied IS-A relationship between ChildClass and ParentClass. Why do you want to do this?
I don't think you can "unimplement" it but you could check if it is an instance of the parent class. Is the interface yours? If so you could extend it to include an "IsObjectDerived" method with semantics that it returns true iff the class only derives from object. Since you are writing the class all you would need to do is implement it in the parent and have it return true if the object is of class Parent and false otherwise.
You could also do this with reflection by checking the superclass of the current class and make sure it is object. I'd probably do it this way since then implementing classes can't lie. You may want to look a tutorial on reflection in Java that I found.
[EDIT] In general I agree that this seems unnecessary in a reasonable design, but it can be done.
Since inheritance, the basis of OOP polymorphism, denotes an is-A relationship - your question seems to request a way to redefine "is" relationships to be "is not" relationships.
That won't work.
Go back to some introductory object-oriented texts or online material and study what object-oriented means: polymorphism, encapsulation, and identity.
Strip off identity, and you've got COM/ActiveX and stolen credentials.
Strip off encapsulation and nobody is safe.
Strip off polyphism's type rules and you basically have nothing is necessarily what it says it is.
If you want a situation like that, then program in "C". Don't mess around with pretending to write OOP code using OOP language features. Just use struct to hold your data. Put unions everywhere. Use typecast with abandon.
Your program likely will not work reliably but you will be able to circumvent any restrictions languages like Java and C++ have introduced to make programs more reliable, easier to read, and easier to write/modify.
In a dynamic programming language like SmalTalk or Python, you can essentially rip the wings off a butterfly at runtime. But only by changing/corrupting the type of the object.
Doing so does not buy you anything. There are coding/design techniques and design patterns that let you accomplish any "good" result that you might be after that are similar to this.
It is best if you think of what exactly you are trying to do in your application, and then try to find the safest/simplest way to accomplish that using sound techniques.
I think you should take this problem as a clear indication that your interface and class design is flawed. Even if you could do it in Java (and I don't think you can) you shouldn't.
How about re-factoring ParentClass so you have the SomeInterface implementation separate from that which you want in ChildClass. Maybe you need a common base class for ParentClass and ChildClass.
I fail to see how this would be sound practice, but you could alter a class dynamically using the excellent package Javassist created by Shigeru Chiba et al. Using this, you can add and remove features from classes and then use instances of these classes without saving as classfiles.
Dynamic, interesting and totally confusing for anyone else. Use with care is my advice, but do play around with it as it makes you a better programmer in my opinion.
(I believe ASM works in a similar fashion, but I have not tried it so far. It does seem to be very popular amongs the non-java language creators working on the JVM, so it is probably good.)
Maybe you have a specific case where a better solution could be devised, but for the generic case you need some black magic. Eventually Javassist could be used "hack" your objects but I'm not so sure.

Is OOP & completely avoiding implementation inheritance possible?

I will choose Java as an example, most people know it, though every other OO language was working as well.
Java, like many other languages, has interface inheritance and implementation inheritance. E.g. a Java class can inherit from another one and every method that has an implementation there (assuming the parent is not abstract) is inherited, too. That means the interface is inherited and the implementation for this method as well. I can overwrite it, but I don't have to. If I don't overwrite it, I have inherited the implementation.
However, my class can also "inherit" (not in Java terms) just an interface, without implementation. Actually interfaces are really named that way in Java, they provide interface inheritance, but without inheriting any implementation, since all methods of an interface have no implementation.
Now there was this article, saying it's better to inherit interfaces than implementations, you may like to read it (at least the first half of the first page), it's pretty interesting. It avoids issues like the fragile base class problem. So far this makes all a lot of sense and many other things said in the article make a lot of sense to me.
What bugs me about this, is that implementation inheritance means code reuse, one of the most important properties of OO languages. Now if Java had no classes (like James Gosling, the godfather of Java has wished according to this article), it solves all problems of implementation inheritance, but how would you make code reuse possible then?
E.g. if I have a class Car and Car has a method move(), which makes the Car move. Now I can sub-class Car for different type of cars, that are all cars, but are all specialized versions of Car. Some may move in a different way, these need to overwrite move() anyway, but most would simply keep the inherited move, as they move alike just like the abstract parent Car. Now assume for a second that there are only interfaces in Java, only interfaces may inherit from each other, a class may implement interfaces, but all classes are always final, so no class can inherit from any other class.
How would you avoid that when you have an Interface Car and hundred Car classes, that you need to implement an identical move() method for each of them? What concepts for code reuse other than implementation inheritance exist in the the OO world?
Some languages have Mixins. Are Mixins the answer to my question? I read about them, but I cannot really imagine how Mixins would work in a Java world and if they can really solve the problem here.
Another idea was that there is a class that only implements the Car interface, let's call it AbstractCar, and implements the move() method. Now other cars implement the Car interface as well, internally they create an instance of AbstractCar and they implement their own move() method by calling move() on their internal abstract Car. But wouldn't this be wasting resources for nothing (a method calling just another method - okay, JIT could inline the code, but still) and using extra memory for keeping internal objects, you wouldn't even need with implementation inheritance? (after all every object needs more memory than just the sum of the encapsulated data) Also isn't it awkward for a programmer to write dummy methods like
public void move() {
abstractCarObject.move();
}
?
Anyone can imagine a better idea how to avoid implementation inheritance and still be able to re-use code in an easy fashion?
Short answer: Yes it is possible. But you have to do it on purpose and no by chance ( using final, abstract and design with inheritance in mind, etc. )
Long answer:
Well, inheritance is not actually for "code re-use", it is for class "specialization", I think this is a misinterpretation.
For instance is it a very bad idea to create a Stack from a Vector, just because they are alike. Or properties from HashTable just because they store values. See [Effective].
The "code reuse" was more a "business view" of the OO characteristics, meaning that you objects were easily distributable among nodes; and were portable and didn't not have the problems of previous programming languages generation. This has been proved half rigth. We now have libraries that can be easily distributed; for instance in java the jar files can be used in any project saving thousands of hours of development. OO still has some problems with portability and things like that, that is the reason now WebServices are so popular ( as before it was CORBA ) but that's another thread.
This is one aspect of "code reuse". The other is effectively, the one that has to do with programming. But in this case is not just to "save" lines of code and creating fragile monsters, but designing with inheritance in mind. This is the item 17 in the book previously mentioned; Item 17: Design and document for inheritance or else prohibit it. See [Effective]
Of course you may have a Car class and tons of subclasses. And yes, the approach you mention about Car interface, AbstractCar and CarImplementation is a correct way to go.
You define the "contract" the Car should adhere and say these are the methods I would expect to have when talking about cars. The abstract car that has the base functionality that every car but leaving and documenting the methods the subclasses are responsible to handle. In java you do this by marking the method as abstract.
When you proceed this way, there is not a problem with the "fragile" class ( or at least the designer is conscious or the threat ) and the subclasses do complete only those parts the designer allow them.
Inheritance is more to "specialize" the classes, in the same fashion a Truck is an specialized version of Car, and MosterTruck an specialized version of Truck.
It does not make sanse to create a "ComputerMouse" subclase from a Car just because it has a Wheel ( scroll wheel ) like a car, it moves, and has a wheel below just to save lines of code. It belongs to a different domain, and it will be used for other purposes.
The way to prevent "implementation" inheritance is in the programming language since the beginning, you should use the final keyword on the class declaration and this way you are prohibiting subclasses.
Subclassing is not evil if it's done on purpose. If it's done uncarefully it may become a nightmare. I would say that you should start as private and "final" as possible and if needed make things more public and extend-able. This is also widely explained in the presentation"How to design good API's and why it matters" See [Good API]
Keep reading articles and with time and practice ( and a lot of patience ) this thing will come clearer. Although sometime you just need to do the work and copy/paste some code :P . This is ok, as long you try to do it well first.
Here are the references both from Joshua Bloch ( formerly working in Sun at the core of java now working for Google )
[Effective]
Effective Java. Definitely the best java book a non beginner should learn, understand and practice. A must have.
Effective Java
[Good API]Presentation that talks on API's design, reusability and related topics.
It is a little lengthy but it worth every minute.
How To Design A Good API and Why it Matters
Regards.
Update: Take a look at minute 42 of the video link I sent you. It talks about this topic:
"When you have two classes in a public API and you think to make one a subclass of another, like Foo is a subclass of Bar, ask your self , is Every Foo a Bar?... "
And in the minute previous it talks about "code reuse" while talking about TimeTask.
The problem with most example against inheritance are examples where the person is using inheritance incorrectly, not a failure of inheritance to correctly abstract.
In the article you posted a link to, the author shows the "brokenness" of inheritance using Stack and ArrayList. The example is flawed because a Stack is not an ArrayList and therefore inheritance should not be used. The example is as flawed as String extending Character, or PointXY extending Number.
Before you extend class, you should always perform the "is_a" test. Since you can't say Every Stack is an ArrayList without being wrong in some way, then you should not inheirit.
The contract for Stack is different than the contract for ArrayList (or List) and stack should not be inheriting methods that is does not care about (like get(int i) and add()). In fact Stack should be an interface with methods such as:
interface Stack<T> {
public void push(T object);
public T pop();
public void clear();
public int size();
}
A class like ArrayListStack might implement the Stack interface, and in that case use composition (having an internal ArrayList) and not inheritance.
Inheritance is not bad, bad inheritance is bad.
You could also use composition and the strategy pattern.link text
public class Car
{
private ICar _car;
public void Move() {
_car.Move();
}
}
This is far more flexible than using inheritance based behaviour as it allows you to change at runtime, by substituting new Car types as required.
You can use composition. In your example, a Car object might contain another object called Drivetrain. The car's move() method could simply call the drive() method of it's drivetrain. The Drivetrain class could, in turn, contain objects like Engine, Transmission, Wheels, etc. If you structured your class hierarchy this way, you could easily create cars which move in different ways by composing them of different combinations of the simpler parts (i.e. reuse code).
To make mixins/composition easier, take a look at my Annotations and Annotation Processor:
http://code.google.com/p/javadude/wiki/Annotations
In particular, the mixins example:
http://code.google.com/p/javadude/wiki/AnnotationsMixinExample
Note that it doesn't currently work if the interfaces/types being delegated to have parameterized methods (or parameterized types on the methods). I'm working on that...
It's funny to answer my own question, but here's something I found that is pretty interesting: Sather.
It's a programming language with no implementation inheritance at all! It knows interfaces (called abstract classes with no implementation or encapsulated data), and interfaces can inherit of each other (actually they even support multiple inheritance!), but a class can only implement interfaces (abstract classes, as many as it likes), it can't inherit from another class. It can however "include" another class. This is rather a delegate concept. Included classes must be instantiated in the constructor of your class and are destroyed when your class is destroyed. Unless you overwrite the methods they have, your class inherits their interface as well, but not their code. Instead methods are created that just forward calls to your method to the equally named method of the included object. The difference between included objects and just encapsulated objects is that you don't have to create the delegation forwards yourself and they don't exist as independent objects that you can pass around, they are part of your object and live and die together with your object (or more technically spoken: The memory for your object and all included ones is created with a single alloc call, same memory block, you just need to init them in your constructor call, while when using real delegates, each of these objects causes an own alloc call, has an own memory block, and lives completely independently of your object).
The language is not so beautiful, but I love the idea behind it :-)
Inheritance is not necessary for an object oriented language.
Consider Javascript, which is even more object-oriented than Java, arguably. There are no classes, just objects. Code is reused by adding existing methods to an object. A Javascript object is essentially a map of names to functions (and data), where the initial contents of the map is established by a prototype, and new entries can be added to a given instance on the fly.
You should read Design Patterns. You will find that Interfaces are critical to many types of useful Design Patterns. For example abstracting different types of network protocols will have the same interface (to the software calling it) but little code reuse because of different behaviors of each type of protocol.
For some algorithms are eye opening in showing how to put together the myriad elements of a programming to do some useful task. Design Patterns do the same for objects.Shows you how to combine objects in a way to perform a useful task.
Design Patterns by the Gang of Four

Categories