It seems you've made a little progress with inheritance but I don't think you get the point of polymorphism yet. You can help yourself tremendously by writing and experimenting with code that actually compiles and runs. None of the code that you posted will actually compile.
Java is case-sensitive and the keyword is
public, not
Public.
You should also try to follow
standard Java coding conventions, particularly when it comes to capitalization of names. Following conventions makes your programs easier for others to read.
Now, as far as polymorphism is concerned, it is really about the ability to use a reference to a class in your program and not care whether or not the object that's actually referenced is an instance of that class or an instance of one its subclasses. Inheritance can also play a role here but polymorphism can also be achieved through interfaces, as explained in that second article I referenced before.
However, the code that you gave doesn't really show the power of polymorphic behavior.
Consider this class hierarchy:
In this hierarchy, Payment is a superclass and CashPayment and CheckPayment are its subclasses. Payment defines a
showDetails() method and its subclasses inherit and override it. Each has it's own implementation of
showDetails() that behaves differently from the others.
The following is how you would see polymorphic behavior in action:
Lines 3-7 create an array that contains three new objects: a Payment, a CashPayment, and a CheckPayment object. Line 9 sets up a loop that iterates over the payments array. The call on line 10 is polymorphic because the variable
p is declare to be a
Payment but the actual object that it will reference will change from a Payment, to a CashPayment, to a CheckPayment as the for-loop iterates over the array. In this example, the three different types of objects that the reference variable
p is able to work with are the different "forms" referred to by the definition of polymorphism. That is, even though the code declares the loop variable
p as a Payment object, it will still work with a
CheckPayment object or a
CashPayment object because these are just two special "forms" of
Payment.
If you decide to add new subclasses of Payment later on, you could expand the payments array to include new kinds of Payment objects and the code on lines 9 and 10 will still work without any modification.
In summary, polymorphism is about writing code that uses a reference of type S that will still work with objects that are subclasses of S, even those that will only be created some time in the future! When designed and used properly, taking advantage of polymorphism can lead to code that is simpler, more robust, and more flexible.