r/javahelp • u/Java_beginner66 • Jun 12 '18
Can't wrap my head around Polymorphism
Read some and watched some about it, but I can't seem to quite get it, and the people of javahelp never disappoint.
I don't even think I understand it well enough to ask a proper question about it. But, is it only useful for method overriding?
And what is the difference between referencing a superclass while making a new instance of subclass, rather than just going 1:1?
as in
Superclass class1 = new Subclass(); // this is considered polymorphism
Subclass class2 = new Subclass(); // What is the advantage of the above?
The way i Interpret this, is that method overriding wont work on class 2, since if you don't override Superclass method, it wouldn't have anything to fall back on? But a class2 method would still override the superclass method right?
I'm just really confused about this topic still, so I can't explain very well what I don't understand.
1
u/MrSquicky Jun 12 '18
I'm going to take it up a step to Inheritance, because I think that is both usually taught incorrectly and core to understanding polymorphism. Warning: this is going to be long and quite possibly boring and pointless.
The main goal of inheritance is to collect common data and functionality at the most appropriate level. Appropriate level here means that the given level has all the information and functionality to do whatever it is supposed to do *and nothing else*.
That concept of "only what you need and nothing else" can be called abstraction and is basically the holy grail of a well architected program. It allows for the greatest amount of decoupling and code reuse, among a host of other benefits.
There's a concept in programming related to this of declarative versus imperative programming, or "I'll tell you what I want to be done" versus "I'll tell you exactly what I want to be done." When people talk about encapsulation, they are basically talking about how you design so people can use your code in a declarative way. To achieve abstraction, you should always prefer declarative to imperative constructions. I promise (well, hope actually) that this will make sense later. The two of them together basically explain the point behind polymorphism
There are three types of inheritance that have three different types of abstraction and three types of elements that correspond roughly to them.
The first type is the contract, often known as the api. This exists to let people know how to use a thing. It says here's what I can do, here's what you need to tell me to do it, and here's what I'll give you back after I do it. This is purest form of declarative programming. Using an api (assuming that the underlying code works correctly) means that you only ever have to know what you want something to do and manage the information that it doesn't already know and never have to think about how it is actually going to be done or supply any of the data or services internal to the thing you are calling.
The contract deals with the declarative aspect of programming and should always be preferred. The interface element is the most direct representation of this, but really any public methods on a class form the api for that class.
The other two types concern themselves with abstracting (or encapsulating) the imperative aspects of a program. When classes are going to share some data or functionality, you shouldn't be repeating them across multiple class definitions. So, you create a superclass to contain all the shared elements and create subclasses of this that should only contain the details specific to the exact use case for that subclass.
There are two cases for this.
The first is when the shared functionality depends on something that it can't know, that is specific to the individual subclasses. You need to guarantee that they are going to be able to do a thing and need to be able to call that thing, even if it is not implemented at the superclass level. So, you create an abstract class that adds the declaration of that thing to the contract of the class.
The second case is when there is core shared functionality defined at the superclass level but one or more subclasses have implementation details that extend the superclass behavior. In this case, you can have a concrete superclass that is extended by concrete subclasses that override the method. The subclass implementation should almost always only include the extension logic and should call the superclass implementation as well.
---
So what does all that have to do with polymorphism? Polymorphism is the mechanism by which these things are achieved. In your code, you should always be referring to the highest level in the inheritance hierarchy that you can. This gives you the most decoupling, which allows you the flexibility to use anything that fulfills the contact for that level. It also aids in people understanding your code, as it lays out the important parts of whatever you are doing and does not clutter up what you need to understand with irrelevant details.
Because you designed things polymorphically and Java understands that, you can stay at the highest level possible when you using the declarative api, probably of the interface, but Java will be able to pick out the correct imperative implementation based on the actual class type of the object that you are dealing with.
This is important from a design/function perspective when you are declaring things like method parameters. It's less so like in what you are talking about in the second part with declaring a variable as either of the superclass or the subclass. But, when you are in the mindset of always choosing the highest inheritance level, using a lower than seemingly necessary level will suggest to you that there is a reason that was chosen. The choices you make when you step out of the standard way of doing things should be intended to communicate information to the people reading the code.
0
Jun 12 '18
[deleted]
1
u/Java_beginner66 Jun 12 '18
Could you go a bit more in depth on your last sentence? My understanding is still like this:
You use a superclass as a base, and if the subclass happens to override it's method, then that's polymorphism.
(Also, I do think I have a proper enough understanding of super/subclass relationship to understand Polymorphism. I'm just really slow on some concepts)
0
Jun 12 '18
[deleted]
2
u/Java_beginner66 Jun 12 '18 edited Jun 12 '18
I understand where you're going with this, but I can't really see it's practical use on a bigger scale. Could you just mention one practical example where this is actually usefull? Where Polymorphism actually solves something, not just strings flying around?
Either way, I appreciate the effort you put into this answer.
1
u/dablya Jun 12 '18
When you see polymorphism, think substitution.
Imagine you have a phone book and a phone.
public interface PhoneBook { PhoneNumber lookup(Name name); } public interface Phone { Connection dial(PhoneNumber phoneNumber); } public interface Connection { void deliver(Message message); }Your client code looks like this:
public class Caller { private PhoneBook phoneBook; private Phone phone; public Caller(PhoneBook phoneBook, Phone phone) { this.phoneBook = phoneBook; this.phone = phone; } public void call(Name name, Message message) { PhoneNumber number = phoneBook.lookup(name); Connection connection = phone.dial(number); connection.deliver(message); }Thanks to polimorphism, you have the ability to implement PhoneBook, Phone, Connection in various ways and the Caller will work as expected.
You can have a:
public FilePhoneBook implements PhoneBook { ... }or a database one:
public JdbcPhoneBook implements PhoneBook { ... }And polymorphism allows you to substitute one or the other when initializing the Caller. The caller will continue to lookup numbers based on names without having to care whether the numbers are being loaded from a database or a file.
0
Jun 12 '18
[deleted]
1
u/Java_beginner66 Jun 12 '18
Oh, using it as a parameter makes it so much more clear for me! I always forget how dynamic programming is, and have a hard time applying the concepts to various contexts. Thanks!
1
Jun 12 '18
Your example makes sense to me, but I think you're confusing polymorphism with inheritance in your explaination.
Dynamic polymorphism is method overriding, which is a tool that can be used with inheritance to reduce code complexity.
Static polymorphism is method overloading, which doesn't require any inheritance, it can be done in the same class.
0
Jun 12 '18
[deleted]
1
Jun 12 '18 edited Jun 12 '18
You examples make sense, but your explanation doesn't.
The idea is the same, but different. Interface is more of a can-do while
polymorphisminheritance is an is-a relationship.Edit:
Inheritance and polymorphism are independent of each other and can operate without one another.
The easiest way to understand the difference is think of driving your friends car. You don't know the model number, you've never driven it, but you are able to drive it despite the fact you never have. You may be able to drive a lot of different cars without ever driving them before. This is polymorphism.
Inheritance is like what you said, you have your super-class and sub-class and the sub-class inherits super-class methods and variables (provided they are of qualifying access modifiers). You can have car and truck extend vehicle.
Polymorphism can be achieved through inheritance, but it's not required.
2
u/TheTimeToLearnIsNow Jun 12 '18
Polymorpishm
You may be getting too involved in the alcohol example up above.
0
Jun 12 '18
[deleted]
2
u/AutoModerator Jun 12 '18
You seem to try to compare
Stringvalues with==or!=.This approach does not work in Java, since
Stringis an object data type and these can only be compared using.equals().See Help on how to compare
Stringvalues in our wiki.Your post is still visible. There is no action you need to take. Still, it would be nice courtesy, even though our rules state to not delete posts, to delete your post if my assumption was correct.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
62
Jun 12 '18
[removed] — view removed comment
4
4
u/nascentt Jun 12 '18
I have to say this was quite a brilliant answer. Thanks for this, I think I learned from it too.
3
3
Jun 12 '18
I wish I read this before my exam last Friday. Thanks for clearing it up for me!. If only everything was explained using alcohol 😑
2
2
u/kegui Jun 12 '18
So much clearer than my lecture notes and stack overflow comments that I traveled through trying to understand the mysterious polymorphism thing the lecturer kept referring to.
2
1
u/AFricknChickn Jun 12 '18
Just throwing this out there since no one has explained this yet, another advantage of referencing Superclass is that if you later decide to refactor your code to use DifferentSubclass, you don't have to go around and change all of the declaration types.
Unless the most-specific type is required, it will almost always be more flexible to use the most-generic type. I'm sure you've seen lines of code like this before: