Importance of Inheritance and when to use Getters and Setters

I am new here to the Ranch and I like the whole idea of the ranks and staff here. This is the first time I made an account. I previously looked around the forum a few months ago and I love how the staff is Friendly and so Active and so Educated. That astounded me. Amazing.
As I digress, I'm new to Java and coding entirely but love the concept of it.

My question is When to use Inheritance vs reusing code. And When should I use getters and setters. I will use my lines of code but for the love of all. I can't see how or when to use it.

and this is the child class

why when I run this program can't otherTest() see test() and what is the best way to
go about doing this Having a parent Class with all sorts of variables and methods that the child can run on but updating each value like having every Child class to have a different name age description mana MP AP? Or is inheritance not for this?
Code is greatly Appreciated and You have an active member here!!!

I'm not exactly sure what problem you're running into (you didn't post the code that actually uses these classes), but I'm guessing it has something to do with your use of static fields and methods. Start by removing the word static everywhere, recompile, and see if that solves the issue.

One other thing: Java variables have names starting with a lowercase letter, whereas classes have names starting with an uppercase letter. The sooner you adopt that practice, the less you'll confuse others reading your code

why when I run this program can't otherTest() see test()

What do you mean by that? Both methods should be be able to call one another.

Want a quick answer?
When to use getters and setters? almost always.
When to use inheritance? Java lets you build programs from outside to the inside, instead from bottom
to the top. This helps maintaining and updating code easier. Inheritance is one of the ways java achieves that. For example....
Theres a class movableCharacter.
You can make a class npc that has his move() method replaced by an AI, and a class player
that uses the input scanner of his class to move.
Why is this important? Because you can say Object.move() and it wont matter if it is an npc object or a player object and it will still move with no errors.

Hi,
* Inheristance is good it give us a nice to tool to acheive reusablity, maintenablity. However, this tool has also some limitations, in java we can only inherit from one class, Inheretence can also break the open closed principle. A nice alternative to have in your software tools is the composition; the strategy pattern * If getters and setters are good or not depends on the type of the object you are designing and the programming style you are following. In the OO getter and setter can break the encapsulation and the Low of Demeter principle
Regards

As Tim has pointed out, if your code uses the static keyword a lot, then your design is off. Static means that a field or method is a member of a class of objects, not an instance of an object. And since Java is Object Oriented, we want to try and make everything as much about instances of objects as possible.

Let's consider the 'Name' field, which hereafter I will call 'name' instead, as should you. When you make it static, you're saying "Every NPC that will ever exist, share the exact same name". Changing the name of one NPC will change the name of all NPCs. When you don't make it static, you're saying "Every NPC has their own name, which may or may not be equal to the name of another NPC".

Static fields should be used for one purpose and one purpose only: Declaring constants. A constant is a value that will never change normally. For the constant to change, the code itself must change. A good example is Math.PI. It's value will not change, it represents a fixed known value. The developers might change the code and recompile it to make it more accurate, but its meaning doesn't change. Usually constants are strings for fixed identifiers and keys, or numeric.

Static methods are used when you want to write behavior that doesn't depend on instance fields. While static variables are bad, static methods aren't bad in their own right, but if you have a lot of them it just means you are probably not using the language it was intended to be used. After all, we usually want our behavior to be based on fields of object instances.

Now let's get to your questions. When to use getters and setters? The answer is as little as possible. You want to keep information contained inside an object as much as possible, and let the object modify itself or interact with other objects in reaction to events. So try to reformulate methods that affect your object in a way that closer resembles events that might happen. For instance, instead of saying setDamage(int), you might want to say something like injure(Weapon) instead, and the NPC itself determines how much it is injured, based on what weapon it was hurt with and other private information it contains, which might include armor that the NPC is wearing or how nimble they are. Often, you will want to get rid of setters entirely. For instance, why would you want to change the name of an NPC after it has received one when it was created? Use constructors to give fields an initial value that can't be changed later.

For getters, only expose them when the rest of your application really needs them. If you want to display health bars in your application, then you obviously need to be able to get the health of an NPC. If you want to keep health a secret, then why expose the getter in the first place? Even then, expose accessors in steps: If they're only required in the current package, then don't make them public. Make them public if you want to be able to access them from everywhere.

I changed your class a little bit to demonstrate some concepts. Don't take it as a precise example of the code you must write. Programming is as much personal taste as it is science.

I renamed the class to Creature, because it's usually better to write out acronyms, NonPlayerCharacter might be a bit verbose, and Character is already a class of the Java standard API. The class is final to prevent it from being extended. You should always make classes final unless you intend to extend them, and if so, you must really design them well for it. There are a lot of complex things you must take into account when allowing your class to be extended.

The class is package private, and so are its constructor and methods. Only make them public when you need to be able to access them outside of the package that the class is in.

The fields are all instance fields (non-static) and most of them are final to prevent them from being changed. Why would you allow the name or the maximum health of an NPC to be changed after they've been created? If you want to be able to change the max health, in response to events like leveling up or drinking some magic potion, you can always make the field non-final in a later version of the code. The initial values for these fields are set in the constructor, and can not be changed through setters.

With the healthIndication() method I gave an example of how you can query an object for information, without exposing all the internal details of the object through getters. HealthIndication is an enum (a finite collection of constants) that gives rough estimates of how much a creature was injured. This is what it could look like:

As you can see in both types, the non-private methods and constructors check their parameters to see if no invalid values were entered.

Stephan van Hulst

Saloon Keeper

Posts: 10136

214

posted 1 month ago

F Lucas wrote:When to use getters and setters? almost always.

You mean, almost never, unless you meant "always access fields through methods, rather than directly". Simple getters and setters don't really add a lot of behavior to a class. Getters usually are fine, but only add them when you need them.

You can make a class npc that has his move() method replaced by an AI, and a class player
that uses the input scanner of his class to move.

You can achieve the same thing with composition and the strategy pattern. For instance, you could create an NPC with a MovementStrategy where one strategy is implemented by entering input through a keyboard, and another is implemented as an AI. Actually extending a class should mostly be done if you want to add new methods.

Stephan van Hulst wrote: You mean, almost never, unless you meant "always access fields through methods, rather than directly". Simple getters and setters don't really add a lot of behavior to a class. Getters usually are fine, but only add them when you need them.

I'm going to be contrary again. This goes all the way back to my C++ days.

There are two things that explicit set/get methods offer over direct property access.

First, should it be necessary to attach additional functionality to the set/get process, you need a method. In almost all cases, that's something that you shouldn't do - set/get should be both idempotent as well as lacking in side functionality, but there are exceptions to every rule. And, of course, on "set" methods, you might want to assert only certain values as valid "set" values.

The second is a bit shakier. These days, debuggers can be configured to throw breakpoints on both set and get of variables. In less civilized times, that wasn't so, and thus the advantage of using a method, since you could set a code breakpoint.

However, even today you don't always have a debugger when you need it. You don't run production systems under a debugger, you might want to do paranoid value checking in critical code, stuff like that. You might be going crazy because you know that a value's being used, but you don't know what the accessor is, and without a debugger, only a manually-generated stack trace can help.

So, as a rule, I very much recommend avoiding direct access in favor of get/set. Many IDEs can automate the grunt work of creating the code, so it's minimal work and maximal flexibility. And, give modern optimizers, not likely to cost you anything in run-time overhead over direct access.

Incidentally, the Java Persistence Architecture (JPA) offers 2 different ways to access Entity properties - either via direct (field) access or via property method (get/set) access. It's got to be all one or all the other, however, since JPA re-works the access mechanisms internally.

When it comes to destroying a civilization, gas chambers cannot hold a candle to echo chambers.

Also, something I feel obliged to bring out separately. DON'T mix direct-access and set/get functionality on the same object!

As I mentioned, JPA won't even allow it, but regardless, when you have both kinds of access, you can never really tell where things are being accessed or modified, meaning that you can end up with a real mess.

And finally, using get/set is good for deprecation and maintenance. One of the real turn-offs using Hungarian notation in C++ for me was that I'd often change the types and implementation of properties. For example, from a boolean to an integer to an enumeration and so forth. In which case the very name of the variable became a lie. With access functions, you can outsource a member property and the move is transparent to the callers of the "get" method. Or, delete it entirely and throw an exception on the accessor if the property is no longer used without making compiles fail - just throw an Exception if someone tries to use it anyway (and mark the method as @deprecated. This kind of stuff is invaluable when you have to do emergency fixes and is one of the reasons I dropped Microsoft in favor of Java. I'm in a bad enough mood when I get dragged into work at 3am to begin with!

When it comes to destroying a civilization, gas chambers cannot hold a candle to echo chambers.

Stephan van Hulst

Saloon Keeper

Posts: 10136

214

posted 1 month ago

I don't think what I'm saying is contrary to your point Tim. Accessors are better than direct field access. I was saying that people shouldn't blindly add accessors for every field of an object, if the outside world doesn't need access to those properties at all.

Stephan van Hulst wrote:I don't think what I'm saying is contrary to your point Tim. Accessors are better than direct field access. I was saying that people shouldn't blindly add accessors for every field of an object, if the outside world doesn't need access to those properties at all.

Private properties. Yeah. No User-serviceable parts inside.

Although you might sometimes give them package-scope accessors for the benefit of unit-testing or private scope if there's a chance for subclasses needing them.

When it comes to destroying a civilization, gas chambers cannot hold a candle to echo chambers.