This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Interfaces (interface/abstract class) are not abstractions?
My knowledge of interfaces is quite limited.
I'm trying to understand them better. What purpose exactly do they serve and when would it be advisable to use them?
Thanks
You are asking a question that fills multiple chapters of most OO text books. I think the best way to answer questions like these is to provide resources, so:
http://en.wikipedia.org/wiki/Interface_(Java)
http://livedocs.adobe.com/flex/3/html/help.html?content=04_OO_Programming_10.html#135768
Or your favorite OO programming book.
In a nutshell, implementing an interface is a little bit like extending a class, except that the interface does not implement the methods you inherent, your class must do that itself. Also, you can implement multiple interfaces. For example, I can create an abstract class Animal and then Flyable and Quackable interfaces. Now class Bat extends Animal and implements Flyable. Class Duck extends Animal and implements both Flyable and Quackable. Class DuckCall can also extend Quackable, etc. You can pass objects to methods based on their interfaces also.
In PHP at least, they're basically just a way to set some restrictions on your objects to make Polymorphism more manageable - that is to say ensure different type of objects can all walk like a duck.
In other words - just a way to programatically ensure your objects have certain members and methods, and throw an error if they don't.
The way I see it, interfaces are used in a similar way to electrical connectors: they define the signals that go in and out of a device so that you don't have to care what exactly is plugged in as long as it respects those rules.
For example, take an mp3 player and it's headphone jack. The engineers that build your mp3 player don't have to care what kind of headphones you will be using on it, and that is possible because of the jack interface.
They program your player against that interface, and then any type of headphones will work as long as they have the jack with the right size. They can even be speakers, they still work (isn't that cool?).
Furthermore, nobody forbids you to plug in something else in the jack socket, as long as it has a jack plug (it implements the interface). You are free to interpret the signals in whatever way you want, and you can for example build a device that changes color instead of playing music.
OOP interfaces work in a similar way: if you require an interface for the objects that are passed as parameter for a method, the caller can send you any implementation for that interface, and the objects that are sent can interpret the calls in their own way.
Related
I was asked this question in one of my interviews and still dont have answer to it. If by abstraction we only mean , you not able to instantiate object(as applicable for interfaces and abstract classes), so having a private constructor is the answer?
Abstraction is explained in varied ways all over internet . Even using System.out.println is abstraction as we dont know detail behind it .
Using factory classes is also abstraction as we dont know which subclass will be instantiated.
Calling any method within an API is also abstraction.
I am actually confused now, as to what the interviewer wanted as answer.
Abstraction is all about hiding implementation, like how the gas pedal to a car abstracts you from the various complexities in making a car go.
A simple way of doing it is to just use private members. GetActiveServers() could call no private methods, or 5 private methods. That doesn't really matter when we're using it, so long as it works efficiently as needed.
I think he was trying to trick you because of the abstract keyword sort've means something different from abstraction, but it's not entirely unrelated.
Problem
I need to overwrite the method
#Override protected final void layoutChartChildren(double top, double left, double width, double height)
of the XYChart class. Obviously I'm not allowed to.
Question
Why do people declare methods as "final"? Is there any benefit in that?
This answer is just a verbatim quote of text by Richard Bair, one of the JavaFX API designers, which was posted on a mailing list in response to the question: "Why is almost everything in the [JavaFX] API final?"
Subclassing breaks encapsulation. That's the fundamental reason why
you must design with care to allow for subclassing, or prohibit it.
Making all the fields of a class public would give developers
increased power -- but of course this breaks encapsulation, so we
avoid it.
We broke people all the time in Swing. It was very difficult to make
even modest bug fixes in Swing without breaking somebody. Changing the
order of calls in a method, broke people. When your framework or API
is being used by millions of programs and the program authors have no
way of knowing which version of your framework they might be running
on (the curse of a shared install of the JRE!), then you find an awful
lot of wisdom in making everything final you possibly can. It isn't
just to protect your own freedom, it actually creates a better product
for everybody. You think you want to subclass and override, but this
comes with a significant downside. The framework author isn't going to
be able to make things better for you in the future.
There's more to it though. When you design an API, you have to think
about the combinations of all things allowed by a developer. When you
allow subclassing, you open up a tremendous number of additional
possible failure modes, so you need to do so with care. Allowing a
subclass but limiting what a superclass allows for redefinition
reduces failure modes. One of my ideals in API design is to create an
API with as much power as possible while reducing the number of
failure modes. It is challenging to do so while also providing enough
flexibility for developers to do what they need to do, and if I have
to choose, I will always err on the side of giving less API in a
release, because you can always add more API later, but once you've
released an API you're stuck with it, or you will break people. And in
this case, API doesn't just mean the method signature, it means the
behavior when certain methods are invoked (as Josh points out in
Effective Java).
The getter / setter method problem Jonathan described is a perfect
example. If we make those methods non-final, then indeed it allows a
subclass to override and log calls. But that's about all it is good
for. If the subclass were to never call super, then we will be broken
(and their app as well!). They think they're disallowing a certain
input value, but they're not. Or the getter returns a value other than
what the property object holds. Or listener notification doesn't
happen right or at the right time. Or the wrong instance of the
property object is returned.
Two things I really like: final, and immutability. GUI's however tend
to favor big class hierarchies and mutable state :-). But we use final
and immutability as much as we can.
Some information:
Best practice since JavaFX setters/getters are final?
Ok so I was just thinking to myself why do programmers stress so much when it comes down to Access Modifiers within OOP.
Lets take this code for example / PHP!
class StackOverflow
{
private var $web_address;
public function setWebAddress(){/*...*/}
}
Because web_address is private it cannot be changed by $object->web_address = 'w.e.', but the fact that that Variable will only ever change is if your programme does $object->web_address = 'w.e.';
If within my application I wanted a variable not to be changed, then I would make my application so that my programming does not have the code to change it, therefore it would never be changed ?
So my question is: What are the major rules and reasons in using private / protected / non-public entities
Because (ideally), a class should have two parts:
an interface exposed to the rest of the world, a manifest of how others can talk to it. Example in a filehandle class: String read(int bytes). Of course this has to be public, (one/the) main purpose of our class is to provide this functionality.
internal state, which noone but the instance itself should (have to) care about. Example in a filehandle class: private String buffer. This can and should be hidden from the rest of the world: They have no buisness with it, it's an implementation detail.
This is even done in language without access modifiers, e.g. Python - except that we don't force people to respect privacy (and remember, they can always use reflection anyway - encapsulation can never be 100% enforced) but prefix private members with _ to indicate "you shouldn't touch this; if you want to mess with it, do at your own risk".
Because you might not be the only developer in your project and the other developers might not know that they shouldn't change it. Or you might forget etc.
It makes it easy to spot (even the compiler can spot it) when you're doing something that someone has said would be a bad idea.
So my question is: What are the major rules and reasons in using private / protected / non-public entities
In Python, there are no access modifiers.
So the reasons are actually language-specific. You might want to update your question slightly to reflect this.
It's a fairly common question about Python. Many programmers from Java or C++ (or other) backgrounds like to think deeply about this. When they learn Python, there's really no deep thinking. The operating principle is
We're all adults here
It's not clear who -- precisely -- the access modifiers help. In Lakos' book, Large-Scale Software Design, there's a long discussion of "protected", since the semantics of protected make subclasses and client interfaces a bit murky.
http://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620
Access modifiers is a tool for defensive programming strategy. You protect your code consciously against your own stupid errors (when you forget something after a while, didn't understand something correctly or just haven't had enough coffee).
You keep yourself from accidentally executing $object->web_address = 'w.e.';. This might seem unnecessary at the moment, but it won't be unnecessary if
two month later you want to change something in the project (and forgot all about the fact that web_address should not be changed directly) or
your project has many thousand lines of code and you simply cannot remember which field you are "allowed" to set directly and which ones require a setter method.
Just because a class has "something" doesn't mean it should expose that something. The class should implement its contract/interface/whatever you want to call it, but in doing so it could easily have all kinds of internal members/methods that don't need to be (and by all rights shouldn't be) known outside of that class.
Sure, you could write the rest of your application to just deal with it anyway, but that's not really considered good design.
Is it any uml-like modeling tool available that can design (draw) classes and can visually represent QT signals and slots, they connections?
The signal/slog mechanism is essentially a mechanism for registering callbacks. So your question could be paraphrased as: "How do I model callbacks in UML". I'm not sure if there is a good answer since callbacks are not really an object oriented construction. Conceptually the observer pattern would be closest.
You can try Enterprise Architect as it supports UML 2.1 and allow to create user defined diagrams.
These connections are dynamic, so I'm not sure it's even possible to represent them in a static way (as in a diagram).
Also, most often, they are tightly bound in time and code (i.e. you create two objects and then connect them). From the code, it should be pretty obvious what happens and why, making any extra documentation dangerous (since the best it could do was to document the current state and it would always be in danger to be out of date unless it was generated from the source, or rather from data gathered during the runtime of the application).
For example: a compatibility layer between scripting objects (like strings, arrays) or scripting engines( eval() ,readFile() etc.).
Without more context, I'd have to say interfaces as well. Consider that you can represent a function or delegate as an interface with a single method and that abstract classes are just interfaces with some methods potentially already implemented.
That said, it really depends on what you're trying to accomplish. Interfaces lend themselves to cases where you have lots of objects with a common interface but potentially varying implementations. If you are, for example, designing a very simple callback system for plugins (i.e.: let the plugin hook certain events in the host application) then delegates are probably simpler and sufficient for your needs.
Also keep in mind that if you do go with interfaces, you'll probably need some way for the host to instantiate instances. The easiest way to do this is by registering a delegate with the host under some unique name.
Abstract classes are only useful if you want to use interfaces and provide a default implementation of some things. A better solution in that case is to have an actual interface instead, and provide the default implementation as a mixin.
Interfaces have my vote. That way, as long as you define the interface any developer will be able to write something compatible fairly easily without you having to distribute too much code to them.