• Post Reply Bookmark Topic Watch Topic
  • New Topic

Inheritance & getters  RSS feed

 
Karen Guffey
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys, I feel like I'm getting behinder & behinder. We're doing inheritance, which I understand in theory, but putting it into practice is beyond me.

In a practice problem, I'm supposed to have a GeometricObject class & then a Triangle class that extends the GeometricObject class. OK so far.

But what goes in the GeometricObject class, particularly when I have to get input from the user? I can put sideLength1, sideLength2, sideLength3 and String color, but I can't give any values because the user will supply the value. And that's another problem: when I type in System.out.printline("Enter this: "); in the GeometricObject file, Netbeans tells me that it doesn't recognize the class "out."

I need to ask a question about get methods, but I figure that, until I know what goes into the superclass, there's no point in trying to figure out how to get anything out of it.

Thank you.
 
Les Morgan
Rancher
Posts: 768
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Take a look at the Polygon API in Java, it will give you a lot of answers, and also the Shape interface.

Karen Guffey wrote:Guys, I feel like I'm getting behinder & behinder. We're doing inheritance, which I understand in theory, but putting it into practice is beyond me.

In a practice problem, I'm supposed to have a GeometricObject class & then a Triangle class that extends the GeometricObject class. OK so far.

But what goes in the GeometricObject class, particularly when I have to get input from the user? I can put sideLength1, sideLength2, sideLength3 and String color, but I can't give any values because the user will supply the value. And that's another problem: when I type in System.out.printline("Enter this: "); in the GeometricObject file, Netbeans tells me that it doesn't recognize the class "out."

I need to ask a question about get methods, but I figure that, until I know what goes into the superclass, there's no point in trying to figure out how to get anything out of it.

Thank you.
 
Liutauras Vilda
Marshal
Posts: 4660
320
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You mixed up too many things. Please exclude all computer science terminology and try to describe whole problem in 3 sentences or so. Once you do that, likely you'll be asked to provide more details, then maybe more and more without using any computing terminology, until problem become clear to you and everyone else.

It could start similary like:
1. My task is to define and describe a geometric object, which could be a triangle, rectangular or square or oval.
2. All geometric shapes has something in common as colour, surface size...
3. Exact measurements how the geometric shape will be looking like, suppose to be an ability to define during the specific shape creation.
4. After the construct of the shape, should be an ability to calculate its...

And keep going until there is nothing left to add.
 
Jason Bullers
Ranch Hand
Posts: 115
11
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karen Guffey wrote:But what goes in the GeometricObject class, particularly when I have to get input from the user?


Your GeometricObject class should define the general contract for working with GeometicObjects in your system. You'll need to figure out what kind of behaviour you need to support. For example, can I calculate the perimeter of a GeometricObject? How about its area? Whether or not you need to store any fields in that GeometricObject base class depends on whether or not those fields would be meaningful to have shared between all the subclasses. You mentioned Color, so maybe that's something you would want to store in GeometricObject since every derived class has a Color.

This really starts getting into the realm of design tradeoffs, though. Given what you've listed, I can think of at least three ways I might try implementing it. And I'm sure if I explained those approaches here, there would be others who would agree or disagree with them, and may even have some completely different implementation ideas! Design is an art as much as it is a science. What will help you here is exactly this:

Liutauras Vilda wrote:Please exclude all computer science terminology and try to describe whole problem in 3 sentences or so.


The clearer you can define the problem (and in this case, what your teacher is trying to teach with this exercise), the easier it is to find a good design for your class hierarchy.

One point definitely worth making is with respect to getting input from the user: this is not the responsibility of GeometricObject or any of the subclasses. Create another class that has your main method in it and is the runner of your application. Its job is to read user input and construct triangles, etc.
 
Karen Guffey
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whew! It's actually a relief to know I'm not supposed to get user input in one of the class files. But what's the point of including any class attributes in a superclass or even a subclass if they get their value in the main class? Just to initialize them?

What the textbook is trying to get me to do is use a subclass & superclass. So what MY problem actually is is trying to figure out why I need to do that. Or to figure out how to do that even if I don't need to do it.

The problem with calculating area anywhere is that the value will be in the main class. I imagine that's the purpose of a get method--to get the value from the main class. But a calculateArea method would have to be in the Triangle subclass because you calculate area differently in other GeometricObjects. Or maybe that's a way to show off knowledge of overriding.

If I could just figure out something that needed to be in the superclass to avoid repetition (other than the declaration of variables), I think I'd be in business. Or at least have a reasonable starting place.
 
Campbell Ritchie
Marshal
Posts: 55774
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karen Guffey wrote:. . .
What the textbook is trying to get me to do
. . .
Which textbook?

Textbooks have to teach inheritance because it is a standard technique. It is more difficult to learn when inheritance is actually a good thing to use and when you should use something different. Yes, using different area and perimeter methods is a good way to use overriding.

What is a main class? It should probably be something which only starts off your app. You will want a class maybe called ShapesDemo with a run method and a main method and precious little else. Everything else goes in different classes. You will probably want a class which deals with keyboard input too.
 
Steffe Wilson
Ranch Hand
Posts: 165
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karen Guffey wrote:Whew! It's actually a relief to know I'm not supposed to get user input in one of the class files. But what's the point of including any class attributes in a superclass or even a subclass if they get their value in the main class? Just to initialize them?


Its trying to teach one of the key points of OO. It may seem overkill for this exercise to be creating all these objects when you could stick all the values in local variables, but go with it so you can learn how its done on bigger applications.

Objects (which I guess you know are instances of a class) store all the information pertaining to a single specific instance of a 'thing'. In your case a shape. But it might be a student, or a bank account, or an aircraft. So when your main class has read in all of the details for one specific shape from the user you can then pass that data to the relevant shape constructor, eg Triangle(side1, side2, side3, color) or whatever, passing in the details and the constructor stores them in the fields belonging to that shape. You now have an object that represents that shape and you have a reference to it so you can use that shape in the rest of your program.

Karen Guffey wrote:What the textbook is trying to get me to do is use a subclass & superclass. So what MY problem actually is is trying to figure out why I need to do that. Or to figure out how to do that even if I don't need to do it.


Maybe search online for example programs demonstrating java inheritance. Briefly: you might have a parent class called Shape that has general shape data that applies to all shapes (eg color). Then you could have specific shape classes that extend Shape. Eg Circle, circle could have a diameter, other shapes such as triangle would not have a diameter so this is something specific to circles, that's why diameter would not be appropriate to store in a field in Shape, its not general, its shape-specific.

Karen Guffey wrote:The problem with calculating area anywhere is that the value will be in the main class. I imagine that's the purpose of a get method--to get the value from the main class. But a calculateArea method would have to be in the Triangle subclass because you calculate area differently in other GeometricObjects. Or maybe that's a way to show off knowledge of overriding.


You are on right lines. The formula for calculating the area of a shape is shape-dependent, so as you say each shape class will need a method to return the area. You are also right about override and maybe you have come across abstract methods? (hint!)

Once you've got an area method for each class you can call it from your main test method, something like this:

Even looping through all your objects.

Karen Guffey wrote:If I could just figure out something that needed to be in the superclass to avoid repetition (other than the declaration of variables), I think I'd be in business. Or at least have a reasonable starting place.


Anything that is common across all shapes is a good candidate for the superclass.
 
Jason Bullers
Ranch Hand
Posts: 115
11
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:What is a main class? It should probably be something which only starts off your app. You will want a class maybe called ShapesDemo with a run method and a main method and precious little else. Everything else goes in different classes. You will probably want a class which deals with keyboard input too.

Fair point. For a small program, I think that starts to get into the realm of over-engineering, though. To be honest, I didn't even think of bringing up the best practice of the main class being a runner and nothing else. Thanks for clarifying that

Karen Guffey wrote:
But what's the point of including any class attributes in a superclass or even a subclass if they get their value in the main class? Just to initialize them?

Yup. When you instantiate your shapes, you are creating a new object in your system. Recall what objects are: little bundles of state that have behaviour associated with them. They model things, and so just like real things, they will have attributes and actions they can perform (or actions that can be performed on them).

Karen Guffey wrote:What the textbook is trying to get me to do is use a subclass & superclass. So what MY problem actually is is trying to figure out why I need to do that.

I think you are already starting to answer this question on your own here:

Karen Guffey wrote:But a calculateArea method would have to be in the Triangle subclass because you calculate area differently in other GeometricObjects. Or maybe that's a way to show off knowledge of overriding.

Let's add another shape to the mix, say Square. So now we have something like this:


Now, what about calculating area? Is that a behaviour (conceptually, forget about how you would actually calculate it) that should apply to every GeometricObject? I would say yes. So we add that to the contract of what it means to be a GeometricObject. Do we have any state that's going to be common to all GeometricObjects? You suggested Color, so let's add that in. Now GeometricObject is an abstract class: it has some implementation details (storing a Color) and it defines a general contract for GeometricObjects (calculating area):



Now, what do we need to calculate areas, and where does that information live? Well, that's an interesting puzzle. Are all of your shapes polygons? Maybe you can maintain a list of side lengths in the super class. If not, you might need to store that information in the subclass instead (what's the side length of a circle?).
 
Liutauras Vilda
Marshal
Posts: 4660
320
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After all given nice advices, it could also help for you to draw a diagram to visualise whole picture.
 
Karen Guffey
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason: did you write my textbook??? (Which is, as Campbell asked, Introduction to Java Programming by Daniel Liang.) What you wrote looks very much like what's there...but seeing it here makes me think that it's just a skeleton. Am I right? In the textbook, the comments are formatted in a way that makes them more distracting than helpful. And I HATE the textbook. When you're taking an IT skills class, wouldn't it make sense to have an online textbook that provides a practice exercise after small chunks of information?

Since I have you here (unlike the author), let me ask: WHERE am I gettingColor() from? The color is going to be user input. So I guess what I need to know is how to implement the method.

Also, I keep reading about the "this" keyword & seeing examples of it, but I'm still not getting it. Why do you have to say this.color in the GeometricObject constructor? It's set in brackets, so it couldn't belong to anything else unless it's passed as a parameter, right?

Steffe: Thanks for your help. You say,
Anything that is common across all shapes is a good candidate for the superclass.
There are a few attributes they have in common, but the value of those attributes is unknown. It's hard for me to see why it's necessary to have a superclass just to declare variables when I'm going to have to give them a value in each subclass, since it makes sense to me just to do both of those things at once, but apparently that's the way it's done. To me, that's like making a nice wooden box (real wood, not pressed wood) & then not doing anything with it. A lot of time & trouble for nothing!
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karen Guffey wrote:But what's the point of including any class attributes in a superclass or even a subclass if they get their value in the main class?

Because very little - in a program or in real life - is entirely self-contained.

A cat is a feline, which is a mammal, which is an animal. Your bank account is (probably) a current account and a personal - as opposed to corporate - account. Your phone is more than likely a smartphone, which itself is an Android, or an iPhone (if you can afford it).

We categorise almost everything, and there will be things that are true for (or that can be done by) a more generalised "parent" type that aren't true for its more specialised "child" - so doesn't it make sense to store all that stuff in the super-type rather than repeat it for every sub-type?

HiH

Winston
 
Steffe Wilson
Ranch Hand
Posts: 165
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karen Guffey wrote:Steffe: Thanks for your help. You say,
Anything that is common across all shapes is a good candidate for the superclass.
There are a few attributes they have in common, but the value of those attributes is unknown. It's hard for me to see why it's necessary to have a superclass just to declare variables when I'm going to have to give them a value in each subclass, since it makes sense to me just to do both of those things at once, but apparently that's the way it's done. To me, that's like making a nice wooden box (real wood, not pressed wood) & then not doing anything with it. A lot of time & trouble for nothing!


Its not quite like that. Say you were writing a college management application. You want to record data about all the people that go to that college. All those people will have common data like name, address, date of birth, phone number etc. So you can create a super class called Person to hold that data. But there is other data that only pertains to students, eg class grades, subjects being studied, etc. For this you need a Student class. And then there will be staff, they will have different data to the students, eg salary, job title, etc. For this we will need a Staff class. Now notice that staff and students alike will need the attributes we defined in the Person class. So what we do is when we define our Staff class we extend the Person class. That means that the Person attributes are all automatically inherited by the Staff class. Its all merged into one, in effect. When the admin people enter a new staff record on the computer they type all the data in and the program then constructs a Staff object, the constructor fills in all the fields including those defined by the Person class that it extends.
Same with the Student class. Students are Persons too (well most of them ;-) ) so you have your Student class extend the Person class.

I think maybe you would benefit by writing some code and playing around with this concept to get it straight in your head. Its a difficult thing to grasp at first I know.

 
Steffe Wilson
Ranch Hand
Posts: 165
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Implementation of my previous example. Put this in a file called College.java and compile and run.



You'll get this output:



Note the comments on lines 34 and 51. These are key to inheritance. Make sure you understand these lines.

Suggest you try to implement a Staff class definition, create a staff object in the main method (similar to line 47) and some print statements similar to lines 49 52.

 
Jason Bullers
Ranch Hand
Posts: 115
11
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karen Guffey wrote:Jason: did you write my textbook??? ... And I HATE the textbook.

Thankfully I did not write it

Karen Guffey wrote:What you wrote looks very much like what's there...but seeing it here makes me think that it's just a skeleton. Am I right?


Right. There's definitely more to fill in, such as the calculations, how you'll handle tracking the side lengths, and how you'll deal with getting user input.

Karen Guffey wrote:Since I have you here (unlike the author), let me ask: WHERE am I gettingColor() from? The color is going to be user input. So I guess what I need to know is how to implement the method.


Where is entirely up to you. As the class was written above, it doesn't care, as long as it gets a colour. If you want to hard-code that like in my example, that's fine. If you want to write some code that randomly creates a colour, great. If you want to write a class that handles user input, reads a string like "red" and turns that into the Color.RED object, that's perfect too. Again, where the colour actually comes from is not important as far as GeometricObjects are concerned.

Karen Guffey wrote:Also, I keep reading about the "this" keyword & seeing examples of it, but I'm still not getting it. Why do you have to say this.color in the GeometricObject constructor? It's set in brackets, so it couldn't belong to anything else unless it's passed as a parameter, right?

this references the object you are currently working with. In the way I've used it, it makes the distinction between the parameter color and the field of the same name. this.color is the field, while color is the parameter. I could also have written it like so:



Karen Guffey wrote:There are a few attributes they have in common, but the value of those attributes is unknown. It's hard for me to see why it's necessary to have a superclass just to declare variables when I'm going to have to give them a value in each subclass, since it makes sense to me just to do both of those things at once, but apparently that's the way it's done. To me, that's like making a nice wooden box (real wood, not pressed wood) & then not doing anything with it. A lot of time & trouble for nothing!

Hmm... you seem focused on knowing what the value of the attributes is. Why does their value matter? When you are writing a class, you are establishing a blueprint for creating objects of that type. You are saying what attributes those objects can have and what behaviour those objects have. Imagine you had six different classes that are all subclasses of your GeometricObject class. Now say you wanted to add a new attribute that is common to all of them, let's say a boolean called filled that determines whether or not the shape should be filled with the colour. You would put this new attribute in the super class and all the six subclasses would now have that attribute. It doesn't matter that some of the actual objects you create are filled and some are not. What matters is that it's a shared attribute common to all those different types of GeometricObject.
 
Karen Guffey
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You guys are really putting a lot into this for me. Thank you.

Jason--You're right: I don't see the importance of a blueprint if no object that uses it uses anything from it. But I'm going to work under the assumption that if I learn to create objects this way, I'll eventually come upon something that actually does make the whole thing more efficient if I put it in the superclass. Also, thank you for explaining "this." "

Steffe--OK, I DON'T understand those comments. But it takes me a while to wrap my head around everything that's going on. Thank you for providing code for me. I'm going to study it until I'm able to understand & apply it. Of course, I'm absolutely going to have questions along the way!
 
Steffe Wilson
Ranch Hand
Posts: 165
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karen Guffey wrote:Steffe--OK, I DON'T understand those comments. But it takes me a while to wrap my head around everything that's going on. Thank you for providing code for me. I'm going to study it until I'm able to understand & apply it. Of course, I'm absolutely going to have questions along the way!

No worries, I'm studying for a Java certification so I'm writing as many code examples as I can so this is all part of my practice too. :-)
 
Jason Bullers
Ranch Hand
Posts: 115
11
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karen Guffey wrote:Jason--You're right: I don't see the importance of a blueprint if no object that uses it uses anything from it. But I'm going to work under the assumption that if I learn to create objects this way, I'll eventually come upon something that actually does make the whole thing more efficient if I put it in the superclass.


I think we might be talking past each other on this point, probably because I'm misunderstanding exactly where your confusion lies. So let's try this:

Let's consider the colour attribute again. Say you have Square and Triangle, both of which are GeometricObjects. How would you represent these classes and specifically the color attribute in code?
 
Karen Guffey
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason! I started doing it & finally got what you're saying!!!

One more hopefully simple question: if a subclass inherits from a superclass, & then a sub sub class inherits from the subclass, does the sub sub class inherit from the superclass? I'm guessing not, because there's an attribute in a superclass that I can use in the subclass but that isn't recognized in the sub sub class. Is there a way to make it recognized in the sub sub class? Thanks!
 
Jason Bullers
Ranch Hand
Posts: 115
11
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karen Guffey wrote:Jason! I started doing it & finally got what you're saying!!!

One more hopefully simple question: if a subclass inherits from a superclass, & then a sub sub class inherits from the subclass, does the sub sub class inherit from the superclass? I'm guessing not, because there's an attribute in a superclass that I can use in the subclass but that isn't recognized in the sub sub class. Is there a way to make it recognized in the sub sub class? Thanks!


Excellent!

What you are describing is an inheritance hierarchy. Your intuition is unfortunately wrong on this one; the sub sub class will inherit from its superclass's superclass. As an example:

 
Karen Guffey
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pffft. The variable in my sub sub class in Netbeans was flagged, & the message was that it wasn't recognized. I played around with the word "super," but that didn't work out. I got rid of it...& then the variable that had been flagged ceased to be flagged. Not gonna lose sleep over THAT one.

OK, before I can figure out the answer to your question about red squares, I have to know something. "Shape" looks like a constructor. Can you have a constructor that isn't the same name as the class? Because I don't see a class called Shape. Is there any chance that's a mistake & you meant to call it "Square"? If that were the case, I'd say that all squares are red because that color is assigned to "color" in the constructor that creates squares. Rectangle, on the other hand, has a color attribute but no value assigned to it, so if you make some other sort of Rectangle, you could make it a different color.
 
Jason Bullers
Ranch Hand
Posts: 115
11
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yup, you're right that it was a mistake on my part. That should be the Square constructor, not Shape. And you are exactly right about how the color works.

Out of curiosity, what was the code that was giving you an error in your IDE?
 
Karen Guffey
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


This was in a sub sub class; "itemName" was declared in the granddaddy class. I didn't have "calories" or "cost" there when "itemName" was flagged. After I put "super" in, had it flagged, moved it around, & finally got rid of it, "itemName" was fine, & then so were the other variables.

I've been multitasking & getting a start on our unit assignment. Part of the assignment was "Once you have your inheritance hierarchy defined, implement the toString method for each class." So I was going to put one in each class. But after figuring out what you'd been talking about, I figured I could put it in the superclass & then just call it for whatever object I needed to. And it works!!!
 
Jason Bullers
Ranch Hand
Posts: 115
11
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure what you changed to get the IDE to find that field, but if you have a field in the "granddaddy class" that is declared as private, it will not be visible to any of the sub classes. If you need a field to be visible to descendants, consider making the field protected or providing a getter method.

toString() in the superclass makes sense for creating a String representation of all the common attributes. You can build up more detailed String in the subclass by overriding toString(), calling the super method and appending the extra information.
 
Campbell Ritchie
Marshal
Posts: 55774
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karen Guffey wrote:Jason: did you write my textbook??? . . .
No, he just collects the royalties
 
Campbell Ritchie
Marshal
Posts: 55774
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason Bullers wrote:. . . consider making the field protected or providing a getter method. . . .
A getter method surely. Variable should always be private; any access should be via a getXXX method. The getXXX methods would be available in subclasses. Some methods do not need to be overriddenYou can now see how those methods are called from the toString method so you can have a square side 5 and print it out as
A Square area 25.000000 perimeter 20.000000
The advice you have been given is standard programming practice, so it is hardly surprising you can read the same in other places.
 
Jason Bullers
Ranch Hand
Posts: 115
11
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:No, he just collects the royalties...

Oh how I wish

Campbell Ritchie wrote:A getter method surely. Variable should always be private; any access should be via a getXXX method. The getXXX methods would be available in subclasses.


Very true. And if whatever you provide access to through the getter method should not part of the public API of the class, then make that getter protected so that subclasses can use it. This way, your innards stay private, but you can still provide a window to them with the narrowest visibility needed. It's worth noting that starting with a protected getter for something you only intend to be used by the subclass is "safer" than making that getter public right off the bat; it's much easier to widen visibility than it is to narrow it.
 
Campbell Ritchie
Marshal
Posts: 55774
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another possibility: put all your classes in a package, with the getters having package‑private access.
Anything used outside the package can have protected or public access. You can probably wrap that package in a sealed .jar to make sure nobody gets access to add classes inside your package.
 
Karen Guffey
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I still don't get getters. But let me see if I can try to apply what Campbell has said to my bit of code above, & you guys can tell me where I'm wrong, maybe.



itemName, calories, & cost are in the superclass. The above code is in its subclass. What I need to do is make the variables private & then use a get method to access them, right? I'd need getitemName(), getcalories(), & getcost()? That can't be right, because everything after "get" in Campbell's examples is capitalized, so those must not be primitive variables. That is, if one get method is getArea(), Area cannot be, according to naming conventions, an int or double, right? So what is it? What exactly am I getting if it's not a primitive or an object? And where is it coming from? That is, how does the getter know where to look for whatever it's looking for?

Also, if I have to use a regex in a toString() or anywhere else, I'm in even worse trouble. I'm having a hard enough time figuring out code in regular English. You guys are nerds, right? So you watch "Star Trek." Assuming you do, there's an episode in classic "ST" where there's a killer on this planet the Enterprise visits, & it turns out that he's inhabiting the body of this little bald guy. But the little bald guys sounds really scary when he's found out & inhabits the ship's computer, laughing like a maniac & repeating the word they've discovered is a term for a terrible evil: "Regek! Regek!" That's what I think of when I read about regex.
 
Steffe Wilson
Ranch Hand
Posts: 165
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Karen Guffey wrote:I'd need getitemName(), getcalories(), & getcost()? That can't be right, because everything after "get" in Campbell's examples is capitalized, so those must not be primitive variables. That is, if one get method is getArea(), Area cannot be, according to naming conventions, an int or double, right?

I can understand your confusion on that. A getter for the field "cost" should be called getCost(). Because it follows the naming convention for a method, first letter lower case, then capitalized words after.

 
Liutauras Vilda
Marshal
Posts: 4660
320
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Once again in simple words:

There is nothing special with "getters" or "setters". These are called like this because of convention, either they get you a value or set. Actually these are special, but not in the way you think they are.
Another thing. You have been told to keep variables with "private" access modifier. Advice was good, always do like this for instance variables when you implement classes, unless you have been told or forced to do differently.
Why? because imagine you have (sorry for boring class name) Bank class:
If it has no private access modifier, it means, anyone else, from "AccountHolder" (bank client/customer) can mess up with this balance, because it is publicly accessible. And direct accessibility is a dangerous thing, which means bank customer can change his balance himself by doing In order do not let this happen (let people steal money from bank and change their actual balance to their wannabe) you need to provide public interface, where you could let to bank account holders to know their current balance, withdraw money and similar under Bank class control. In simplified words control could be achieved by so called "setter" methods. We call them setters because they set some kind of values, in different words, they change state of the object. And these methods in most cases are "public", in some cases can be "protected" (has been explained already "why?" by Jason B). So, if you make variable "balance" as private, it means it is accessible only within that class where it is defined (this case in Bank class). In order to retrieve that value (bank account holder wants to check his balance) you need to provide public interface for that - "getter" method:
As mentioned earlier, "setter" methods lets you assign values, as well as to add some checks before assign them in order do not let assign values which are not appropriate with company policies, standards or similar. Lets take example:
So, you know that no one will in your company won't get more than 3500 salary without you knowing that first. These are just examples to get the main idea.
 
Karen Guffey
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, I have followed my instructor's instructions & gone from a program that worked to one that doesn't. I'll try to keep it as simple as possible.

I have a 3-level hierarchy. This is the top class:


This is the middle class:


This is the bottom class:



And this is the class with the main method:



When I run the program, it prints out default values for the 3 parameters--null, 0, 0.0--rather than the ones given for crispy. I'm obviously not getting (as in a get method) or overriding something. My professor specifically said to set the parameters this way. Before, I'd set the values like this:



in the main method, & it ran like it was supposed to. Of course, that was before I went back & made everything private.

Can you guys tell how to make the program print the toString statement with the values in the parameters instead of the default values? Thank you.
 
Steffe Wilson
Ranch Hand
Posts: 165
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
check your constructors.
 
Karen Guffey
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator






right? I don't see the problem. All the parameters are identical. And, to be honest, Netbeans created the "super" lines when I clicked on the red flag, so if that's the problem, it's not my fault! ; )
 
Jason Bullers
Ranch Hand
Posts: 115
11
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your base class has three fields. You need to assign something to those fields before they will have values. Since you don't have any setters (or any need for them as far as I can tell), I'd recommend adding the keyword final to all of those private fields in the base class. The IDE will very quickly tell you that you've not assigned anything to those variables and maybe (I'm not familiar with Netbeans) help you fix the problem.
 
Karen Guffey
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But if I make them final & give them a value, won't all objects have the same name, cost, & calories?
 
Jason Bullers
Ranch Hand
Posts: 115
11
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it would be worth having a read through this tutorial. It should clear up some of the confusion you seem to be having. I suspect you should be able to solve your problem after having a look through there. If not, let us know what still has you stumped and we'll go from there.
 
Steffe Wilson
Ranch Hand
Posts: 165
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also don't forget to take a look at the example I posted earlier in this thread.
http://www.coderanch.com/forums/posts/list/657633#3048709
 
Karen Guffey
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've been reading the tutorial Jason linked, & I just looked back at Steffe's post. I've tried a couple of things, to no avail. I'm about to take a break...but I'll be back! Thanks!
 
Karen Guffey
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, guys, I went through the entire tutorial & tried 3 or 4 things that didn't work. One of them was the THIS operator. Netbeans flagged it & said that the package had to be private. Then I went to Steffe's example & saw that she'd used THIS. So I went back, did that, & let Netbeans do whatever the heck it was wanting to do. Now the program runs. But it's not in my head. For now, I'm just going to be satisfied that it works.

Can you tell me when & where (I'll wait & see if I can figure out why) I'm going to call one of the getMethods?

Thanks. It's late, I'm tired, & in about 7 hours I have to go into a class where yesterday a student asked if I cared if they passed & then said, "I feel like you know from experience that this will be hard, & you haven't done anything to make it easier for us." You Brits can see why our high school education has gone down the tubes. This was beginning Spanish, btw. Maybe I should use that line on my Java instructor.
 
Jason Bullers
Ranch Hand
Posts: 115
11
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it was a mistake on my part to suggest setting the variables to final and using the IDE to help you find what you were doing wrong. From your last post, I feel like you are leaning way to heavily on the IDE right now and just changing code more or less at random until you make the IDE happy. This is bad! You may end up with a working program eventually, and you'll have no idea why it works. That makes adding to it or debugging it near impossible.

So, let's take a step back. We'll start with your code from a few posts ago:

Karen Guffey wrote:I have a 3-level hierarchy. This is the top class:


This is the middle class:


This is the bottom class:



And this is the class with the main method:




Let's start with main and trace what's happening. You create a new MandMs object called crispy and print it out. How do you create that object? You pass three arguments to its constructor: "Crispy", 300, and .75. These arguments are literal values, and they will be bound to the parameters of the constructor you called. See here:



These variables hold those values that you passed in. Your constructor takes those values as passes them along to the constructor of Sugary by calling super(). Now, what does that constructor do?



It does the same thing. Note here that itemName, calories, and cost hold the same values as in the MandMs constructor, but they are entirely different variables. The fact that they have the same name doesn't mean anything.

So now we call the Snack constructor and pass all those values along again. What does the "granddaddy" Snack constructor do?



It does... nothing. Remember, that argument list in the constructor is local to the constructor. That means that those variables are only defined within the curly braces (scope) of that constructor. This is exactly equivalent:



This should make it fairly obvious that the constructor really is doing nothing. Nowhere do you capture those values that were passed in! Your object has three fields: itemName, calories, and cost. Nothing sets those fields to a value. (Technically they are set to "default" values of 0 for numbers and null for objects, which is why you get the results you get). You need to capture those arguments in order to properly construct your object:



Now that you've captured the values, your object will be properly constructed and you should see the results you are expecting when it prints out.

A few other points on the code:

  • Declaring the three fields as final is sensible if they should never change. It prevents you from forgetting to set the values and catches you if you reset a value by mistake. There are other benefits that I don't want to get in to right now because they are fairly advanced.[list]
    [list]Unless you are intentionally hiding some of that state (which I don't think you meant to do in this case), all your getters should be public. Also, I would think you would want your Snack class to be public as well.
  • You could probably make the constructors of the abstract classes protected since they will only be called by subclasses (you can't say new Snack("Crispy", 300, ,75))
  • It's good practice to create variables of the widest type. In main, try this: Snack crispy = new MandMs("Crispy", 300, .75);


  • As for when you might use those getters, consider something like this:
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!