Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Class / Subclass

 
leo donahue
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Specifically, What is lime? Is it a Fruit reference to a Citrus object or the other way around?
Secondly, how many objects are created here?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
lime is a Fruit reference to a Citrus object. The only object I see being created is the explicit Citrus one (it's possible that println() creates some objects behind the scenes, but I don't think you're asking about those.)
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To say the same thing in a lot more words ... you have a variable declared with type Fruit. A variables that holds an object is really just a pointer, a little bit of information about where to find an object in memory. A variable like lime is allowed to point to an object exactly matching the declaration (Fruit) or any subclass (Citrus). When you call lime.method() you run the method on the actual object, whether it is Fruit or Citrus.
We often say the derived class "is a" base class, or "Citrus is a Fruit". That's not always 100% true but as a general concept it tells us we can make a variable of type Fruit point to an object of type Citrus because for this purpose a Citrus is a Fruit.
Hope that helped. Objects are tons of fun, no?
 
Bryan Noll
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good answers.
There's a couple good articles in the Campfire Stories area that explain these concepts well.
http://www.javaranch.com/campfire/StoryCups.jsp
http://www.javaranch.com/campfire/StoryPassBy.jsp
StoryPassBy is the specific one...but it helps to read StoryCups first.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Those are good articles, Brian. After reading them, be sure to follow up with the "How my Dog learned Polymorphism" article, which is right on topic.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic