I've got a task to do polymorphism but I am not entirely sure I understand the concept as per testimony of my teacher.
According to web definitions and examples, this by all means is polymorphism, but they say it is not. Can I please get confirmation?
OversizedParcel.java
public class OversizedParcel implements ParcelType {
public void resolve(PrivateUser user) {
//do theese
//and those
}
public void resolve(LegalUser user) {
//do different thing
//and a completely different thing
}
}
IllegalParcel.java
public class IllegalParcel implements ParcelType {
public void resolve(PrivateUser user) {
//do this
//do that
}
public void resolve(LegalUser user) {
//do a thing
//do a different thing
}
}
(hypothetical class)
public class Main{
private User user; //loaded user
private List<ParcelType> parcels; //assume this contains the loaded parcels already
public static void main(String[] args){
for(ParcelType type : parcels) type.resolve(user);
}
}
Polymorphism can be defined as -
it is the ability of an object to take on many forms
. The most common example of polymorphism could be-
when a parent class reference is used to refer to a child class
object.
So as per your question, in most simplistic way polymorphism can be defined as
ParcelType oversizedparcel = new oversizedParcel();
ParcelType illegalparcel = new illegalParcel();
Here ParcelType can be a oversizedParcel or illegalparcel
So if your understanding is as per my answer, then indeed it is an example of polymorphism.
I'd like to offer a dissenting opinion from what appears to be majority here. Keep in mind that "Polymorphism" is a fairly flexible term, and that what is written here does not necessitate 100% universal truth. This is simply something to aid the balance of thought.
No, what you have written is not polymorphism. This is due to the fact that they instantiate different unrelated objects that simply implement the same interface.
Traditionally, Polymorphism occurs when you have a child object that overrides a parent object's implementation of a method. Hence, there is "multiple forms" of a method that exist at the same time at different levels of the object's vertical hierarchy.
However, interfaces are merely an agreed-upon contract of inputs and outputs that standardize interactions. They don't by themselves hold an instance of the code (we shall exclude default interface methods for the sake of this conversation). Because of this, there is no "Re-definition" of the interface within an object. the same object tree does not instantiate multiple versions of the interface (unless it is through the traditional view of polymorphism).
Even if a method required two arguments of interface ParcelType, it does not necessarily mean polymorphism, it simply means that the method is asking for two 'boxes' of a particular shape and size. These boxes are empty until they are passed into the method as two distinctly different objects that are referenced separately (And not the same method object being overridden by a child object, for example)
Different objects can take advantage of the interface contract, and in a way you can say that it is "Horizontal Polymorphism", but I think this is taking away from the intention of what polymorphism means in the context of Java.
According to the W3School definition, it is indeed polymorphism. Anyway, if your teachers said it is not, they may have been expecting you to do something else.
Polymorphism is, to go further than just an example, an entire concept meaning that you can do entirely different things by using "the same things", or more exactly "things named the same".
Have a look on the Wikipedia definition, which is more complete than any language-specific one, to have a wider view on it.
Polymorphism is having the same thing in different forms. So, Yes this is polymorphism.
I assume that resolve is defined in ParcelType interface. Then the type.resolve calls in for(ParcelType type : parcels) type.resolve(user) are dispatched polymorphically on ParcelType
Related
I have confusion regarding Method Overriding in java.
From it's definition it says :
In any object-oriented programming language, Overriding is a feature
that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its
super-classes or parent classes.
Now, below is one example regarding it :
class Parent {
void show()
{
System.out.println("Parent's show()");
}
}
class Child extends Parent {
#Override
void show()
{
System.out.println("Child's show()");
}
}
class Main {
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.show();
Parent obj2 = new Child();
obj2.show();
}
}
I have doubt at this line :
Parent obj2 = new Child();
I can do the same thing using :
Child obj2 = new Child();
then why I need to declare it with the name Parent class?
What it's purpose?
Like you said, you don't need to declare subclass objects as their parent class, but there are other cases where this may be important, such as when you are trying to make things abstract.
What is Abstraction?
Abstraction is removing everything but the most essential. A really good example you probably already use a ton is Lists.
Whether you are using an ArrayList, a LinkedList, or any other type of Java list, you know that there are certain properties that you can always count on being there, like getting the size of the list, getting a certain element at a certain point, etc.
This DRAMATICALLY simplifies the use of these, and you can interchange them depending on your application. This is all because they are a subclass of List, in which these methods come from.
The ways that an ArrayList, and a LinkedList get and set data are different, but from the perspective of you, the user of these sub classes, the implementation is the same, you just use the classes that were overridden. It's super convenient, because you don't need to know a thing about coding, try whatever you're trying to do with a linkedlist, then with an arraylist, and see whats faster.
What's your part in this?
In the example you gave, it is very simple, and doesn't matter, but say you were making a class that sorted lists in a particular, fun, amazing way.
If you declared everything as just a List, users of your class could pass in both ArrayLists, and LinkedLists, depending on what they were doing, and both would work. So, to be a good programmer, try to keep everything as abstract as possible. It's a good rule to learn early on.
Inheritance allows us to reuse of code, it improves reusability in your java application.
Note: The biggest advantage of Inheritance is that the code that is already present in base class need not be rewritten in the child class.
I am learning Java, I know what inheritance and composition is, I saw numerous examples of polymorphysim showed using inheritance, so my first question is,can same be done using composition? If yes, please show with a small example.
My second question is, can it be said that polymorpysim is basically method overloading and/or is method overiding ? if yes, then why ?
First question
Polymorphism can be achieved in Java in two ways:
Through class inheritance: class A extends B
Through interface implementation: class A implements C.
In the later case, to properly implement A's behaviour, it can be done though composition, making A delegate over some other class/es which do the tasks specified in Interface C.
Example: Let's suppose we have already some class imeplementing interface C:
class X implements C
{
public String getName() {...}
public int getAge() {...}
}
How can we create a new class implementing C with the same behaviour of X? Like this:
class A implements C
{
private C x=new X();
public String getName() {return x.getName();}
public int getAge() {return x.getAge();}
}
Second question
No, polymorphism is not method overloading and/or method overriding (in fact, overloading has nothing to do with Object Oriented Design):
Method overloading consists on creating a new method with the same name that some other (maybe inherited) method in the same class but with a different signature (=parameter numbers or types). Adding new methods is OK, but that is not the aim of polymorphism.
Method overriding consists on setting a new body to an inherited method, so that this new body will be executed in the current class instead of the inherited method's body. This is a advantage of polymorphism, still is not the base of it either.
Polymorphism, in brief, is the ability of a class to be used as different classes/interfaces.
No, not really. Polymorphism and composition or aggregation (composition is a more rigid form of aggregation wherein the composed objects' lifetimes are tied together) are different ways of reusing classes.
Composition involves aggregating multiple objects to form a single entity. Polymorphism involves multiple objects that share analogous behavior.
For example, a Car object might be composed of two Axle objects, a Chassis object, four Wheel objects (which themselves may be composed of a Rim, a Tire, six LugNuts and so on). When you instantiate a Car, your Car constructor would instantiate all the parts that go along with it. That's composition. (Aggregation would use all the same part objects but not necessarily instantiate them in its constructor.)
A Car object might also not be useful on its own, but rather as a blueprint for numerous more specialized implementations of cars, such as SportsCar, SUVCar, SedanCar, and the like. In this case, the Car object might define a Car interface that would define common behaviors such as Steer, HitTheGas and Brake, but leave the implementations of those behaviors to the implementing classes. Then, a consumer of a Car object can declare an object of type Car, instantiate it as any of the implementing classes such as SportsCar, call the methods defined in the Car interface, and get the behavior implemented in the instantiated class. That's polymorphism.
For a decent tutorial on both, with some comparisons, have a look at this. Keep in mind that the UML diagrams have an inaccuracy: while the examples do indeed describe composition as opposed to aggregation, the related UML class diagrams have white diamonds where they should be black. UML class diagram syntax uses a white diamond for class associations that are aggregations and a black one for those that are compositions.
Also, this post has some good information, in particular tdammers's answer halfway down the page.
There is book answer, if one remember about all the firemans are fireman but some are drivers, chiefs etc. There you need polymorphism. There is things you can do with classes and it's a general idea in OOP as language constraints. Overriding is just what you can do with classes. Also permissions and local and/or global scopes. There is default constructor for any class. There is namespace scope, program, class etc.
All Classes and methods are functions but not all functions are methods
You can override class but not method. Those are static or volatile. Cos method can only return the value. So overriding the method has no sense. I hope this will turn you, if nothing, toward how it was meant to be. Inheritance is mechanism how polymorphism works.
My apologies for unintentional mistakes during too much data.
This question already has answers here:
Interfaces in Java - what are they for? [duplicate]
(9 answers)
Closed 9 years ago.
Let's say you have an interface
public interface Change {
void updateUser();
void deleteUser();
void helpUser();
}
I've read that interfaces are Java's way to implement multiple inheritance. You implement an interface, then you have access to its methods. What I don't understand is, the methods don't have any body in the interface, so you need to give them a body in your class. So if you an interface is implemented by more than one class, you need to give the method a body in more than one class. Why is this better than just having individual methods in your classes, and not implementing an interface?
My professor in college once gave a great anecdote to describe polymorphism and encapsulation. It went like this.
Does anyone here know how a soda machine works? (Cue confused glances about why we'd even talk about this.) No? Let me tell you.
You drop in your change, and inside the machine is a little monkey who counts all your change to make sure you put in enough money. When you press the button for your soda, a little light comes on telling the monkey which button you pressed, and if you entered the right amount of change, he grabs your choice and throws it into the little hole for you to grab your soda.
This is the concept of encapsulation. We hide the implementation of the soda machine. Unless it's got one of those fancy, clear windows to let you see the inside, you honestly have no idea how it really works. All you know is that you put in some cash, you press a button, and if you put in enough, you get your drink.
To add to that, you know how to use a soda machine's interface, so therefore as long as the machine's interface follows the usual soda machine interface, you can use it. This is called the interface contract. The machine can be bringing the drinks from Antarctica on a conveyor belt for all you care, as long as you get your drink, it's cold, and you get change back.
Polymorphism is the idea that when you use the soda machine interface, it could be doing different things. This is why encapsulation and polymorphism are closely related. In polymorphism, all you know is that you're using a SodaMachine implementation, which can be changed, and as a result, different things can be done behind the scenes. This leads to the driving concept of polymorphism, which is the ability of one object, the SodaMachine, to actually act as both a MonkeySodaMachine and a ConveyorSodaMachine depending on the machine actually behind the interface.
Probably not word-for-word, but close enough. Essentially it boils down to two concepts: polymorphism and encapsulation. Let me know if you want clarification.
Why is this better than just having individual methods in your classes, and not implementing an interface?
Because if a class C implements an interface I, you can use a C whenever an I is expected. If you do not implement the interface, you could not do this (even if you provided all of the appropriate methods as mandated by the interface):
interface I {
void foo();
}
class C1 implements I {
public void foo() {
System.out.println("C1");
}
}
class C2 { // C2 has a 'foo' method, but does not implement I
public void foo() {
System.out.println("C2");
}
}
...
class Test {
public static void main(String[] args) {
I eye1 = new C1(); // works
I eye2 = new C2(); // error!
}
}
It separates what the caller expects from the implementation. You have a pure set of methods you can call without any knowledge of the implementation. In fact some libraries like JMS and JDBC provide interfaces without any implementations.
This separation means you don't need to know the class of any actual implementation.
An interface allows you to guarantee that certain methods exist and return the required types. When the compiler knows this, it can use that assumption to work with unknown classes as if they had certain known behavior. For example, the comparable interface guarantees that an implementing class will be able to compareTo() some similar object and will return an int.
This means that you can compare anything that implements this interface - so you can sort anything that is Comparable instead of writing one method to sort Strings and another to sort Integers and another to sort LabelledBoxesOfBooks
The interface essentially guarentees that all the methods that inherit it will have its methods, so that you can safely call a method in the interface for anything that inherits it.
It makes it easier to define APIs using interfaces, so that all concrete implementations of the interfaces provide the expected methods in each class.
It also provides a way to implement multiple inheritance, which is not possible (in Java) with straight class inheritance.
The subject says it already:
I am thinking right now about following design-problem: I define an interface for a specific type of object that contains various methods.
Now i have the problem, that different implementations of this interface, need additional/different method-parameters (because the way they are implemented makes this necessary), which i cannot incorporate into the interface because they are not common to all interface-implementations.
Now i realize that interface implementations could come with their own property-files, loading their additional parameters from there, but what if these parameters need to be passed in at runtime?
Currently i can only think of passing in a Map<String, Object> parameters to overcome this problem - since JDK-Classes like DocumentBuilderFactory are doing something very similar by providing methods like setAttribute(String attName, Object attValue) this
seems like a feasible approach to solve this problem.
Nevertheless i would be interested in how others solve issues like this, alternative ideas?
I dont want to derive from the interface and add additional methods, since in my case i would then have to throw NotImplementException from the methods of the base interface.
UPDATE:
What could be eventual problems of the Map-approach? Implementing classes are free to ignore it completely if they cant make use of additional parameters.
Others might check if the Map contains the desired parameter-names, check the type of their values and use them if valid, throw an exception if not.
I have also seen this being used for the abstract class JAXBContext, so it seems to be a common approach..
UPDATE:
I decided to go for the map-approach, since i dont see any obvious disadvantages and it is being used in the JDK as well (yes, i know this does not necessarily mean much :)
Since i cannot accept an answer on this question, i will just upvote. Thanks for your input!
regards,
--qu
You should just initialize each inheritor with its own specific required parameters and let the interface method remain parameter-less, as in:
Interface Runnable:
public interface Runnable {
public abstract void run();
}
Implementation:
public class MyRunnable {
private final String myConcreteString;
public MyRunnable(String myConcreteString) {
this.myConcreteString = myConcreteString;
}
public void run() {
// do something with myConcreteString
}
}
The point of the interfaces is to have something that is common to all implementations. By trying to do this you destroy the whole reason why interfaces exists.
If you absolutely must do that there is a simple enough way that I have used before.
My answer is in C++ because I'm just not that fluent in other languages. I'm sure there are ways to implement this in java as well.
SomeMethod(void* parameterData);
void* parameterData is a pointer to a struct containing your data. In each implementation you know what you are receiving. You can even have a enum to tell you what kind of data you are receiving.
SSomeData* data = (SSomeData)parameterData
EDIT:
Another approach would be to create a new interface for the parameters: IParameterData.
Inside that interface you have 2 methods: GetParameter(name) and SetParameter(name).
For each implementation of your primary interface you create a implementation of IParameterData.
I hope it helps
couldn't you design subinterfaces that extend your (super)interface?
anyhow I see a design problem if you need a method with different parameters depending on the implementation!
edit: code to clarify
interface CommonBehaviour
{
void methodA(int aParam);
}
interface SpecificBehaviour extends CommonBehaviour
{
void methodB(int aParam, int anotherParam);
}
class SpecificBehaviourImpl implements SpecificBehaviour
{
void methodA(int aParam)
{
//do something common
}
void methodB(int aParam, int anotherParam)
{
//do something specific
}
}
CommonBehaviour myObj = new SpecificBehaviourImpl();
EDIT: You may benefit from the Command pattern:
"Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the owner of the method or the method parameters."
(source: wikipedia)
I don't think the Map approach to be any good, I may accept it as a fix of existing code that would allow you to have any parameter number and type, but without formal checks! You're trying to define a common behavior (interface methods) given a variable, runtime, state.
You should introduce parameter object representing a super-set of possible arguments.
In your place, I would consider finding appropriate design pattern to your problem, rather then try to bend the interface methods to suit your needs. Look into Strategy Pattern for starters.
Can you invert the problem, and implement an interface on the user of these objects which they can query for the additional parameters?
So, when you instantiate these objects implementing the common interface, you also pass in (e.g. to their constructor) an object which provides a way of accessing the additional parameters they might require.
Say your interface has a method 'doSomething' taking parameter 'a', but you have an implementation that needs to know what 'b' is inside this 'doSomething' method. It would call 'getB' on the object you provided to it's constructor to get this information.
In my quest to correctly grasp Interface best practices, I have noticed declarations such as:
List<String> myList = new ArrayList<String>();
instead of
ArrayList<String> myList = new ArrayList<String>();
-To my understanding the reason is because it allows flexibility in case one day you do not want to implement an ArrayList but maybe another type of list.
With this logic, I set up an example:
public class InterfaceTest {
public static void main(String[] args) {
PetInterface p = new Cat();
p.talk();
}
}
interface PetInterface {
public void talk();
}
class Dog implements PetInterface {
#Override
public void talk() {
System.out.println("Bark!");
}
}
class Cat implements PetInterface {
#Override
public void talk() {
System.out.println("Meow!");
}
public void batheSelf() {
System.out.println("Cat bathing");
}
}
My question is, I cannot access the batheSelf() method because it only exists for Cat. That leads me to believe that I should only declare from an Interface if I am only going to use methods declared in the Interface (and not extra methods from the subclass), otherwise I should declare from the Class directly (in this case Cat). Am I correct in this assumption?
When there is a choice between referring to an object by their interface or a class, the former should be preferred, but only if an appropriate type exists.
Consider StringimplementsCharSequence as an example. You should not just blindly use CharSequence in preferrence to String for all cases, because that would deny you simple operations like trim(), toUpperCase(), etc.
However, a method that takes a String only to care about its sequence of char values should use CharSequence instead, because that is the appropriate type in this case. This is in fact the case with replace(CharSequence target, CharSequence replacement) in the String class.
Another example is java.util.regex.Pattern and its Matcher matcher(CharSequence) method. This lets a Matcher be created from Pattern for not just String, but also for all other CharSequence there are out there.
A great example in the library of where an interface should've been used, but unfortunately wasn't, can also be found in Matcher: its appendReplacement and appendTail methods accept only StringBuffer. This class has largely been replaced by its faster cousin StringBuilder since 1.5.
A StringBuilder is not a StringBuffer, so we can not use the former with the append… methods in Matcher. However, both of them implementsAppendable (also introduced in 1.5). Ideally Matcher's append… method should accept any Appendable, and we would then be able to use StringBuilder, as well as all other Appendable available!
So we can see how when an appropriate type exists referring to objects by their interfaces can be a powerful abstraction, but only if those types exist. If the type does not exist, then you may consider defining one of your own if it makes sense. In this Cat example, you may define interface SelfBathable, for example. Then instead of referring to a Cat, you can accept any SelfBathable object (e.g. a Parakeet)
If it does not make sense to create a new type, then by all means you can refer to it by its class.
See also
Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces
If appropriate interface types exist, then parameters, return values, and fields should all be declared using interface types. If you get into the habit of using interface types, your program will be much more flexible. It is entirely appropriate to refer to an object by a class if no appropriate interface exists.
Related links
Bug ID: 5066679 - java.util.regex.Matcher should make more use of Appendable
Yes, you are correct. You should declare as the most general type providing the methods you use.
This is the concept of polymorphism.
Your are correct, but you can cast from the interface to the desired pet if you need. For example:
PetInterface p = new Cat();
((Cat)p).batheSelf();
Of course if you try to cast your pet to a dog you cannot call the batheSelf() method. It would not even compile. So, to avoid problems, you could have a method like this:
public void bathe(PetInterface p){
if (p instanceof Cat) {
Cat c = (Cat) p;
c.batheSelf();
}
}
When using instanceof, you make sure you will not try to make a dog bathe himself during runtime. Which would throw an error.
Yes, you are correct. By having Cat implent "PetInterface" you can use it in the example above and easily add more kinds of pets. If you really need to be Cat-specific you need to access the Cat class.
You can call method batheSelf from talk in Cat.
Generally, you should prefer interfaces to concrete classes. Along those lines, if you can avoid using the new operator (which always requires a concrete type as in your new ArrayList example), even better.
This all has to do with managing dependencies in your code. It's best to depend only on highly abstract things (like interfaces) because they also tend to be very stable (see http://objectmentor.com/resources/articles/stability.pdf). Because they have no code, they only must be changed when the API changes...in other words, when you want that interface to present a different behavior to the world, i.e., a design change.
Classes, on the other hand, change all the time. Code that depends upon a class doesn't care how it does what it does, as long as the inputs and the outputs of the API don't change, callers shouldn't care.
You should strive to nail down the behavior of your classes according to the Open-Closed Principle (see http://objectmentor.com/resources/articles/ocp.pdf), that way existing interfaces need not change even when you add functionality, you can just specify a new subinterface.
The old way of avoiding the new operator was by using the Abstract Factory pattern, but that comes with its own set of problems. Better is to use a tool like Guice that does dependency injection, and prefer constructor injection. Make sure you understand the Dependency Inversion Principle (see http://objectmentor.com/resources/articles/dip.pdf) before you start using dependency injection. I've seen a lot of people inject inappropriate dependencies and then later complain that the tool isn't helping them...it won't make you a great programmer, you still have to use it appropriately.
Example: you are writing a program that helps students learn physics. In this program, students can put a ball in various physical scenarios and watch how it behaves: shoot it out of a cannon off a cliff, put it underwater, in deep space, etc. Question: you want to include something about the heaviness of the ball in the Ball API...should you include a getMass() method or a getWeight() method?
Weight depends upon the environment the ball happens to be in. It might be convenient for callers to be able to call one method and get the weight of the ball wherever it happens to be, but how do you write this method? Each ball instance must constantly keep track of where it is and what the current gravitational constant is. So you should prefer getMass(), because mass is an intrinsic property of the ball and doesn't depend on its environment.
Wait, what if you just use getWeight(Environment) instead? This way, the ball instance can just get its current g out of the environment and proceed...better yet, you can use Guice to inject the Environment in the Ball's constructor! This is the type of misuse I often see, and people end up blaming Guice for not being able to handle dependency injection as seamlessly as they would've hoped.
The problem is not Guice here, it's the Ball API design. Weight is not an intrinsic property of the ball, so it's not a property that should be accessible from the ball. Instead, Ball should implement the MassiveObject interface with a getMass() method, and Environment should have a method called getWeightOf(MassiveObject). Intrinsic to the Environment is its own gravitational constant, so this is much better. And Environment only depends upon a simple interface now, MassiveObject...but it's job is to contain objects, so this is as it should be.
Why not simply do this!
Cat c = new Cat();
PetInterface p = (PetInterface)c;
p.talk();
c.batheSelf();
Now we have a single object, which can be manipulated using 2 references.
The reference p can be used to call functions defined in interface and c can be used to call functions defined in class(or superclass) only.