Win a copy of Secure Financial Transactions with Ansible, Terraform, and OpenSCAP this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Rob Spoor
  • Henry Wong
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh
  • Jj Roberts

Question on Polymorphism

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello I started reading a java book. Introduction to Java programming by liang. I have question in polymorphism section of the book. Below are the statements from the book.

An object of a subclass can be used wherever its superclass object is
used. This is commonly known as polymorphism (from a Greek word meaning “many
forms”). In simple terms, polymorphism means that a variable of a supertype can refer to
a subtype object.

Polymorphism means that a variable of a supertype can refer to a subtype object.




I believe superclass cannot be of subclass type. While subclass can be of superclass type and holds superclass type object too with subclass object.

If this is the case, how can superclass type variable can hold subclass type object? Is it not contradicting? Sorry if its basic, please explain in simple terms

Consider below example:




In the code, may I know what is the difference in two statements,


And how are the objects allocated and their behavior in above two statements.
 
Saloon Keeper
Posts: 12827
279
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to CodeRanch!

dasvis das wrote:I believe superclass cannot be of subclass type. While subclass can be of superclass type and holds superclass type object too with subclass object.


Polymorphism is about what types you can assign to variables. Polymorphism means you can assign an object of type Experiment to a variable of type MasterExperiment.

It also means that when you call a method on such a variable, it will invoke the behavior defined in the subtype that you assigned, not the behavior that you defined in the supertype that you used to declare the variable with.

In the code, may I know what is the difference in two statements,


The second statement demonstrates polymorphism. It shows you can assign an Experiment to a variable of type MasterExperiment.

The first statement just demonstrates that the compiler will trust you blindly if you tell it to cast an object, even if it will cause an exception at runtime. You would never write a statement like that. The following example is better:

This program won't throw an exception at runtime, because masterExperiment really does hold a reference to an Experiment (this is polymorphism) and so you can cast the reference back to Experiment and assign it to a variable of type Experiment.
 
Marshal
Posts: 72487
315
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:Welcome to CodeRanch!

Agree; welcome (again).

. . . when you call a method on such a variable . . .

Remember that polymorphism can only be seen at work in instance methods. It doesn't apply to fields, nor to static methods.
 
milind k das
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Stephan van Hulst Thank you for explanation. Your explanation gave me some clarity. Still confused. But I will reading again this topic more detail. Please such some source with explanation in detail including how JVM handles.

@Campbell Ritchie Thank you for posting that. I was about to post my second question on this. Can you elaborate on this why it's not applied on data fields and static methods? Thank you
 
Campbell Ritchie
Marshal
Posts: 72487
315
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That is how the language was designed. Bruce Eckel (Thinking in Java) says that access to class members (as opposed to object members) is determined statically at compile time, which is why they are called static. Access to instance methods and nothing else is determined dynamically at run time by finding the location in the appropriate Class<XXX> object where the method's implementation resides. Result: you shoul  always call static members by ClassName.memberName, and you should never write a field with the same name as a superclass field.
I am afraid that, if you want more information why, you would have to find documents from the development stage of Java® back in 1995/1996, or ask somebody who remembers that development process.
 
lowercase baba
Posts: 12975
66
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Remember that there is the reference type, and the object type.  The reference is the label you apply to an object.  to slightly change your example, let's assume we have
in line 4, you create a generic Mammal object.  You tell java via the cast "I know it doesn't look like a dog, but it really is". The compiler believes you, but at run time, you may encounter issues.

In line 5, you create an actual Dog object, so you don't need a cast.  And since a dog IS-A mammal, everything is fine.  the compiler knows that Dogs can do everything Mammals can.  Even though you have given the actual object a "Mammal" label, that's ok.

(as usual, I'm writing this pre-coffee, so if I've made a mistake, someone will correct me soon).
 
milind k das
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


In the above code, I have Account class in different Package - Chapter9 and class CheckingAccount is in package Chapter11. I have imported the Account and all methods in Account are public. However, in class CheckingAccount, even though the withdraw method I want to override has same signature, @Override is showing error "Method does not override method from its superclass". Please let me know why its not letting me override? What's wrong here?
 
Saloon Keeper
Posts: 8020
70
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Typo error. Check your method names.
 
milind k das
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Carey Brown wrote:Typo error. Check your method names.


ooops!! Thank you very much!
 
Campbell Ritchie
Marshal
Posts: 72487
315
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

milind k das wrote:. . .

No. Don't use java.util.Date. It is badly written. Use one of the  datatypes described here in the Java™ Tutorials.
Use lower‑case writing for package names.
 
Stephan van Hulst
Saloon Keeper
Posts: 12827
279
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Don't use floating point values for anything other than imprecise measurements. Your account balance should be an integer and your interest rate either an integer or a BigDecimal.

IDs should be strings, not integers.

Make the ID and creation time of an account final.

Make all methods that are not intended to be overridden final. When in doubt, make it final.

Perform parameter validation in your mutators. You should not be able to withdraw or deposit negative amounts. Also, check for integer overflows.

Validate class invariants by throwing exceptions. When you try to withdraw more than the overdraft limit allows, throw an exception.

Don't use long sequences of string concatenations. Use a formatter instead.

 
milind k das
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



In this program, System.out.println(list); statement is printing the elements's values in list. My question is, isn't list a reference variable to ArrayList? Is it not supposed to print reference value of "list"?
 
milind k das
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:Don't use floating point values for anything other than imprecise measurements. Your account balance should be an integer and your interest rate either an integer or a BigDecimal.

IDs should be strings, not integers.

Make the ID and creation time of an account final.

Make all methods that are not intended to be overridden final. When in doubt, make it final.

Perform parameter validation in your mutators. You should not be able to withdraw or deposit negative amounts. Also, check for integer overflows.

Validate class invariants by throwing exceptions. When you try to withdraw more than the overdraft limit allows, throw an exception.

Don't use long sequences of string concatenations. Use a formatter instead.



Thank you very much. this has been helpful.
 
bacon. tiny ad:
SKIP - a book about connecting industrious people with elderly land owners
https://coderanch.com/t/skip-book
reply
    Bookmark Topic Watch Topic
  • New Topic