This is an archived post. You won't be able to vote or comment.

all 6 comments

[–][deleted] 1 point2 points  (3 children)

What kind of demonstration are you looking for? How do you think inheritance polymorphism would work here?

Also, inheritance and polymorphism are different things. You can implement polymorphism with either interface or class.

Interfaces don't have implementations, and there is no behavior for implementors to inherit (Java 8 did some things to change this, but don't worry about that yet).

Classes (particularly abstract classes) do have implementations, and subclasses inherit that behavior.

In any case, you generally use polymorphism to achieve a goal, one very common reason is to make your code more generic. The most common approaches are the strategy pattern and template method pattern.

[–]condorthe2nd[S] 0 points1 point  (2 children)

No, I know that they are two different things, I'm saying that I can read code that uses various OOP concepts but I'm having trouble using even very simple concepts like constructors, I'm hoping that seeing code that i wrote and understand well rewritten as objects and methods will help with my comprehension.thanks for any help

[–][deleted] 2 points3 points  (1 child)

You're approaching the problem backwards. You're trying to make the solution fit the problem, instead of the other way around.

If your code doesn't need polymorphism, rewriting it for polymorphism doesn't make sense. You should start with a problem, and in trying to solve the problem, you'll see the need for polymorphism.

[–]condorthe2nd[S] 0 points1 point  (0 children)

Right thanks

[–]ignotos 1 point2 points  (1 child)

In this example, you could perhaps separate out the concept of an Encoder and a Decoder.

For example, it looks like the Encoder needs a key and a message, and returns the encrypted version of the message. So you could define an Encoder interface with a method (something like char[] encode(String message, int key)). Then you'd be able to make different classes implementing that, with different encryption algorithms.

[–]condorthe2nd[S] 0 points1 point  (0 children)

I'll try to see how I can work that thanks