• Post Reply Bookmark Topic Watch Topic
  • New Topic

Inheritance in Java  RSS feed

 
A Rodgers
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm making a vending machine program to practice inheritance and have a few questions. My superclass is a Soda class, and I'm making subclasses like "Orange soda", "Coke", etc. My first question is, what is the point of the subclass inheriting the instance variables of the superclass? If you have to define them again is there any point in the super class having them? Here is an example of this:

My superclass:


My subclass:


Besides not having to write the vendSoda() method again, what is the benefit of inheritance in a situation like this if you have to define all variables again? My second question is, how could I store all of the code strings from all of the different subclasses in one place? (so when the user enters a code it can search for the code entered to give the desired soda)
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are you re-defining them in the sub-class?

also, why do you have the getName in the subclass? Wouldn't it fit better in the superclass? that way you don't need to re-write it in every single subclass - the whole point of inheritance.
 
Campbell Ritchie
Marshal
Posts: 56592
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A Rodgers wrote: . . . the instance variables of the superclass? If you have to define them again . . .
You must not define them again in the subclasses. That would mean you have two copies of each field, and that way lies confusion unbounded.
What you do is create the superclass (maybe abstract) which has the instance fields, which of course have private access. I presume you will have get methods? You use them in the subclasses to gain access if you need it. Actually, define all the methods in the superclass, too. Make the superclass abstract, then all you need in the subclasses is constructors.And that is it. Your subclass can be written completely in 7 lines.
 
Ashwin Rao
Ranch Hand
Posts: 89
C++ Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Inheriting instance variables is useful when the same instance variables are also inherited to other sub-classes. Doing so allows you to model applications close to their real-world counter-part and easier to maintain and future re-use.
I'll try to explain with an example (I'm a beginner myself so don't be too harsh on me if I have made a mistake!! :p)



As you can see if you wanted to make another class say "Vw" or "Porshe" they would have the price and numberOfSeats as instance variables when you make them extend Car. But the real advantage comes when somebody in the future creates a "new" Car type. Then what they have to do is just extend the existing "Car" class and their "new" Car type is good to go.
Another important use of inheritance comes into play when you talk about polymorphism (It's epic by the way :p).
Hope I helped at least a little bit!
 
Campbell Ritchie
Marshal
Posts: 56592
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why on earth do you need to duplicate methods like setPrice()? Since they have public access they will be accessible in all subclasses. you should only override a method when you need different behaviour. This class will work just as well:-But do you really want a Ferrari to be a subclass of Car? And why have you not given those classes constructors?
 
Campbell Ritchie
Marshal
Posts: 56592
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ashwin Rao wrote: . . . the same instance variables are also inherited to other sub-classes. . . .
No, you don't want to inherit the fields. They can be private. What you want to inherit is the behaviour which means the methods.
 
A Rodgers
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've used everything that has been said to simplify my subclasses, but I'm getting an error. When I make the subclass and define the instance variables, it wants another set of brackets around the class. Here is an example:


the error says "Syntax error, insert "}" to complete ClassBody" (line 7) and "Syntax error, insert "{" to complete ClassBody" (line 1). How can I fix this / avoid it in the future?
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At the risk of tooting my own horn for the second time in just a little over an hour, you might want to head over to this thread: http://www.coderanch.com/t/643124/design/implement-vending-application and go over some of my comments about this kind of approach.

Basically, trying to design a class from the bottom-up like this is little more than a thought exercise and guessing game. Coming at the problem from a user's perspective gives you a better view of what behaviors and responsibilities you'll need in your program. Go look at that thread and try to follow the thought and development process I laid out. Caveat: it's a very long thread and I cover a lot of things in it. It can be a little bit daunting to read but those who have persevered through it have said they learned a few things.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can't do that. you should create a constructor for the OrangeSoda class that sets these values.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you find that thread too long then here are a few things for you to consider:

1. Object-orientation is really about behaviors and assigning responsibilities to the appropriate abstraction. Attributes (instance variables) are just pieces of information that allow your abstractions (i.e. Objects) to be self-contained and do their work as independently as possible. Again, the important aspect of objects are their behaviors and how they interact with other objects to get a job done.

2. Before you pack for a trip, you first need to know what you're going to do on your trip, right? Are you going camping, to a conference, to a dance competition, to the beach, etc. So before you start packing your objects/classes with "stuff" (attributes and methods), you have to ask "What am I going to ask this object to do?" That will lead you to list down the behaviors you want the object to exhibit and the bits of information that the object will need to carry out its responsibilities.

3. Sticking with the going on a trip analogy, to know what you are going to need on your trip you also have to consider who is coming along or who you expect to meet during your trip. Do you need to rent a car or are you going to drive your own car? Who's coming along? What are their needs? Who's going to provide for those needs? Are you going to stay at a hotel or are you going to pack a tent and sleep at whatever campsite you happen to find? Similarly, you will need to ask "What other objects will need to do things to help this object get the job done?" These other objects are called "collaborators" and all these objects are going to depend on one another. This is where assignment of responsibilities comes in. Each object will have a job to do, and thus will need to have specific behaviors and information to do their job. You have to figure that stuff out.

So before you get caught up in the thought exercise that you're currently embarking on, try to answer these questions first so that you can get some clarity on what exactly is your end goal for getting these objects to do something for you. And you always have to ask things like "Does it make sense to make grandma over here carry this big backpack as we tour the Grand Canyon?"

 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote:And you always have to ask things like "Does it make sense to make grandma over here carry this big backpack as we tour the Grand Canyon?"

To put the question more directly for your case: Does it make sense to ask a Soda object to vend a Soda? If not, then try describing how, in real life, you get a soda vended out to you.

Fill in the blanks: "As a Customer, I would like to get a Soda from (blank) so that I can quench my thirst."
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One final comment before I give it a rest and let others comment or the OP respond

Perhaps this scenario with the Soda and OrangeSoda and the like is not the best scenario to learn about inheritance. The ideas and relationships you've come up with so far don't make much sense and the use of inheritance seems forced. You don't want to force anything when it comes to coding and design. Things should flow and fit naturally, otherwise confusion and bugs arise.

The mechanism of inheritance is related to polymorphism and minimizing duplication. If two or more objects behave similarly, you don't want to write the same code in two or more places. You want to write the code once and assign that behavior to one thing and have other objects take on or inherit that behavior somehow. As far as polymorphism goes, even when two objects are similar in some aspects, they may also need to behave slightly differently in other aspects. Objects often need to do basically the same thing their "own way". Inheritance can play a role in allowing for polymorphic behavior within a hierarchy of objects.

In your scenario, I don't see these kinds of relationships playing out for Soda and subcategories of Soda. Soda doesn't really have many interesting behaviors, except maybe that it fizzes and often will explode when shaken too hard or combined with a few pieces of Mentos. And for me, attributes like price and name don't really play a big role in considering the use of inheritance. Many objects can have a "name" or "id" attribute but they don't necessarily need to inherit from a single "Named" or "Identifiable" object. If anything, I would use an interface if that kind of commonality needs to be in place.

So maybe you should find some other scenario where you can have a general category of object (the base class) that defines basic, common behaviors. Then have some subcategories (the subclasses) that have the same general behavior but will do them slightly differently from one subclass to another. I know this sounds more like polymorphism than inheritance but like I said, the two kind of go hand in hand. In fact, if you look at the Java Tutorials, Polymorphism is a subtopic of the Inheritance topic.

Speaking of the Java Tutorials, I don't find the examples in them about inheritance and polymorphism particularly useful because they don't really emphasize that common behaviors and responsibilities should be the main considerations for using inheritance.
 
Knute Snortum
Sheriff
Posts: 4287
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A Rodgers wrote:I've used everything that has been said to simplify my subclasses, but I'm getting an error. When I make the subclass and define the instance variables, it wants another set of brackets around the class. Here is an example:


the error says "Syntax error, insert "}" to complete ClassBody" (line 7) and "Syntax error, insert "{" to complete ClassBody" (line 1). How can I fix this / avoid it in the future?


You have to write code in a method. Second, you should either set the properties of the object in a constructor (as was already stated) or setters.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I lied I have one more comment before I leave you be.

Here are some suggestions for scenarios that might be more fitting and interesting to use inheritance with:

1. Stick with the soda idea but think about different bottle shapes and sizes. Now, getting back to the behavior thing and fizzing and Mentos. How would you simulate an experiment with different bottle shapes and sizes to see what shape/size of soda bottle will explode more spectacularly when you plop some Mentos into them? Write code for a common "experiment" that will take different kinds of bottles and put in X number of Mentos into a bottle, and then observe and measure how quickly or violently it explodes. How can the use of inheritance help you code for this scenario?

2. Define some categories of vehicles (trucks, minivans, sedans, sportsCar, etc.) and simulate a test of their towing capacities. Again, you'll write a common test that takes any kind of vehicle, attaches a fixed load to it and observes and measures the vehicle's performance. How can the use of inheritance help you code for this scenario?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!